1. 程式人生 > >java8 stream map根據value排序

java8 stream map根據value排序

List<String> items =
                Arrays.asList("apple", "apple", "banana",
                        "apple", "orange", "banana", "papaya");

        Map<String, Long> result =
                items.stream().collect(
                        Collectors.groupingBy(
                                Function.
identity(), Collectors.counting() ) ); Map<String, Long> finalMap = new LinkedHashMap<>(); //Sort a map and add to finalMap result.entrySet().stream() .sorted(Map.Entry.<String, Long>comparingByValue() .
reversed()).forEachOrdered(e -> finalMap.put(e.getKey(), e.getValue())); System.out.println(finalMap);