Java 8 stream map to list of keys sorted by values

前端 未结 6 1285
夕颜
夕颜 2020-12-03 06:29

I have map Map countByType and I want to have a list which has sorted (min to max) keys by their corresponding values. My try is:



        
6条回答
  •  感动是毒
    2020-12-03 07:13

    You can use this as an example of your problem

        Map map = new HashMap<>();
        map.put(10, "apple");
        map.put(20, "orange");
        map.put(30, "banana");
        map.put(40, "watermelon");
        map.put(50, "dragonfruit");
    
        // split a map into 2 List
        List resultSortedKey = new ArrayList<>();
        List resultValues = map.entrySet().stream()
                //sort a Map by key and stored in resultSortedKey
                .sorted(Map.Entry.comparingByKey().reversed())
                .peek(e -> resultSortedKey.add(e.getKey()))
                .map(x -> x.getValue())
                // filter banana and return it to resultValues
                .filter(x -> !"banana".equalsIgnoreCase(x))
                .collect(Collectors.toList());
    
        resultSortedKey.forEach(System.out::println);
        resultValues.forEach(System.out::println);
    

提交回复
热议问题