Sort keys with the same values ​​& # 8594; LinkedHashMap

I wrote a word program in Java and came up with a list of words and frequencies. The result is currently stored in LinkedHashMap. The results look something like this:

garden-->2
road-->4
street-->5
park-->5
highway-->5

In the above result set stored in LinkedHashMap, how can I sort it only to sort keys with the same frequency. We still want to maintain the frequency order as indicated.

The result will look something like this:

garden-->2
road-->4
highway-->5
park-->5
street-->5

Thanks.

+6
source share
2 answers

, . IDE, , , Comparator#comparing, :

Map<String, Integer> map = new LinkedHashMap<>();

map.put("garden", 2);
map.put("road", 4);
map.put("street", 5);
map.put("park", 5);
map.put("highway", 5);

map = map.entrySet()
         .stream()
         .sorted(Comparator.<Entry<String, Integer>, Integer>comparing(Entry::getValue)
                           .thenComparing(Comparator.comparing(Entry::getKey)))
         .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (k, v) -> {
             throw new IllegalStateException(String.format("Duplicate Key: %s", k));
         }, LinkedHashMap::new));

System.out.println(map);

:

{ = 2, = 4, = 5, = 5, = 5}

, , , , . ( ):

map = map.entrySet()
         .stream()
         .sorted(Comparator.<Entry<String, Integer>, Integer>comparing(Map.Entry::getValue).reversed()
                           .thenComparing(Comparator.comparing(Entry::getKey)))
         .collect(Collectors.toMap(Entry::getKey, Entry::getValue, (k, v) -> {
                throw new IllegalStateException(String.format("Duplicate key %s", k));
         }, LinkedHashMap::new));

: Entry java.util.Map.Entry Collectors java.util.stream.Collectors.

+2

JAVA7 , .

Map<String, Integer> map = new LinkedHashMap<>();

map.put("garden", 2);
map.put("road", 4);
map.put("street", 5);
map.put("park", 5);
map.put("highway", 5);

List<Entry<String, Integer>> list = new ArrayList<>();
list.addAll(map.entrySet());

Collections.sort(list, new Comparator<Entry<String, Integer>>() {

    @Override
    public int compare(Entry<String, Integer> o1, Entry<String, Integer> o2) {
        return o1.getValue()-o2.getValue() != 0 ?  o1.getValue()-o2.getValue() : o1.getKey().compareTo(o2.getKey());
    }
});
System.out.println(list);

: -

[ = 2, = 4, = 5, = 5, = 5]

, , , .

+1

All Articles