Java 8 List into Map

前端 未结 22 2493
半阙折子戏
半阙折子戏 2020-11-22 03:38

I want to translate a List of objects into a Map using Java 8\'s streams and lambdas.

This is how I would write it in Java 7 and below.

private Map&l         


        
22条回答
  •  自闭症患者
    2020-11-22 04:20

    String array[] = {"ASDFASDFASDF","AA", "BBB", "CCCC", "DD", "EEDDDAD"};
        List list = Arrays.asList(array);
        Map map = list.stream()
                .collect(Collectors.toMap(s -> s.length(), s -> s, (x, y) -> {
                    System.out.println("Dublicate key" + x);
                    return x;
                },()-> new TreeMap<>((s1,s2)->s2.compareTo(s1))));
        System.out.println(map);
    

    Dublicate key AA {12=ASDFASDFASDF, 7=EEDDDAD, 4=CCCC, 3=BBB, 2=AA}

提交回复
热议问题