JAVA-Stream-List转换Map

使用Java8的Stream Api,将List转换成Map非常方便。

/**
 * @author wzx
 * @time 2018/8/4
 */
public class ListToMapTest {

    public static void main(String[] args) {
        List persons = new ArrayList();
        persons.add(new Person("wzx1", 10));
        persons.add(new Person("wzx2", 11));
        persons.add(new Person("wzx3", 12));
        persons.add(new Person("wzx4", 13));
        persons.add(new Person("wzx5", 14));
        //Collectors.toMap 参数一:key,参数二:value,参数三:mergeFunction,处理相同key函数
        Map map1 = persons.stream().collect(Collectors.toMap(Person::getName, Person::getAge));
        map1.forEach((k, v) -> System.out.println(k + ":" + v));

        //如果key重复报错
        persons.add(new Person("wzx5", 16));
//        Map<String, Integer> map2 = persons.stream().collect(Collectors.toMap(Person::getName, Person::getAge));
        System.out.println("==================");


        //处理key相同情况
        Map<String, Integer> map3 = persons.stream().collect(Collectors.toMap(Person::getName, Person::getAge, (oldVal, newVal) -> oldVal));
        map3.forEach((k, v) -> System.out.println(k + ":" + v));

        System.out.println("==================");
        ///排序并转换map
        Map<String, Integer> map4 = persons.stream().sorted(Comparator.comparingInt(Person::getAge).reversed())
                .collect(Collectors.toMap(Person::getName, Person::getAge,
                        (oldVal, newVal) -> newVal, LinkedHashMap::new));
        map4.forEach((k, v) -> System.out.println(k + ":" + v));
    }

    static class Person {
        private String name;
        private int age;

        public Person(String name, int age) {
            this.name = name;
            this.age = age;
        }

        public String getName() {
            return name;
        }

        public int getAge() {
            return age;
        }

    }
}

输出结果:

wzx5:14
wzx4:13
wzx3:12
wzx2:11
wzx1:10
==================
wzx5:14
wzx4:13
wzx3:12
wzx2:11
wzx1:10
==================
wzx5:14
wzx4:13
wzx3:12
wzx2:11
wzx1:10

key重复错误:

Exception in thread "main" java.lang.IllegalStateException: Duplicate key 14
    at java.util.stream.Collectors.lambda$throwingMerger$113(Collectors.java:133)
    at java.util.stream.Collectors$$Lambda$3/666641942.apply(Unknown Source)
	at java.util.HashMap.merge(HashMap.java:1245)
	at java.util.stream.Collectors.lambda$toMap$171(Collectors.java:1320)
	at java.util.stream.Collectors$$Lambda$5/186370029.accept(Unknown Source)
    at java.util.stream.ReduceOps$3ReducingSink.accept(ReduceOps.java:169)
    at java.util.ArrayList$ArrayListSpliterator.forEachRemaining(ArrayList.java:1374)
    at java.util.stream.AbstractPipeline.copyInto(AbstractPipeline.java:512)
    at java.util.stream.AbstractPipeline.wrapAndCopyInto(AbstractPipeline.java:502)
    at java.util.stream.ReduceOps$ReduceOp.evaluateSequential(ReduceOps.java:708)
    at java.util.stream.AbstractPipeline.evaluate(AbstractPipeline.java:234)
    at java.util.stream.ReferencePipeline.collect(ReferencePipeline.java:499)
    at cn.wzx.ListToMapTest.main(ListToMapTest.java:26)

你可能感兴趣的:(JAVA,SE,Java,Stream,List转换Map)