快捷搜索: 王者荣耀 脱发

Java8Lambda表达式实现List转Map

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class LambdaTest {
    static
    class Person {
        private Integer id;
        private String name;

        public Person(Integer id, String name) {
            this.id = id;
            this.name = name;
        }

        public Integer getId() {
            return id;
        }

        public void setId(Integer id) {
            this.id = id;
        }

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        @Override
        public String toString() {
            return "Person{" +
                    "id=" + id +
                    ", name=" + name +  +
                    };
        }
    }

    public static void main(String[] args) {
        List<Person> people = new ArrayList<>();
        people.add(new Person(1, "张三"));
        people.add(new Person(2, "李四"));
        people.add(new Person(3, "王五"));
        //1.遍历输出
        people.stream().forEach(p -> {
            System.out.println(p.toString());
        });
        //2.取对象的两个属性,变成Map
        Map<Integer, String> map1 = people.stream().collect(Collectors.toMap(Person::getId, Person::getName));
        //Map<Integer, String> map1 = people.stream().collect(Collectors.toMap(Person::getId, Person::getName, (p1, p2) -> p1));
        map1.keySet().stream().forEach(k -> {
            System.out.println("key=" + k + " value=" + map1.get(k));
        });
        //3.剥离出主键,变成Map
        //Map<Integer, Person> map2 = people.stream().collect(Collectors.toMap(Person::getId, p -> p));
        Map<Integer, Person> map2 = people.stream().collect(Collectors.toMap(Person::getId, p -> p, (p1, p2) -> p2));
        //如果这里的key可能存在重复,增添(p1, p2) -> p1,表示如果重复选前者;同理,(p1, p2) -> p2,表示如果重复选后者
        map2.keySet().stream().forEach(k -> {
            System.out.println("key=" + k + " value=" + map2.get(k));
        });
    }
}

打印结果: Person{id=1, name=‘张三’} Person{id=2, name=‘李四’} Person{id=3, name=‘王五’} key=1 value=张三 key=2 value=李四 key=3 value=王五 key=1 value=Person{id=1, name=‘张三’} key=2 value=Person{id=2, name=‘李四’} key=3 value=Person{id=3, name=‘王五’}

经验分享 程序员 微信小程序 职场和发展