QWERTY
QWERTY

Reputation: 2315

Java count string occurrence and sort in reverse order

I was having some trouble when trying to count the string occurrence and sort them in descending order. Here is the list of sample inputs:

test, test, to, to, to, to, today, tomorrow, today

The desired output is in this order:

to, test, today tomorrow

Here is my code to count the string occurrence and sort them in reverse order:

Map<String, Integer> sortedTextSegmentList = new LinkedHashMap<String, Integer>();
 for (String s : textSegmentList) {
     if (sortedTextSegmentList.get(s) != null) {
         sortedTextSegmentList.put(s, sortedTextSegmentList.get(s) + 1);
     } else {
         sortedTextSegmentList.put(s, 1);
     }
 }

 sortedTextSegmentList.entrySet().stream()
         .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y)-> {throw new AssertionError();}, LinkedHashMap::new
         ));

However, I am getting this output:

test, to, today, tomorrow

When I try to print out:

sortedTextSegmentList.forEach((key, value) -> {
         System.out.println("KEY" + key);
         System.out.println("VALUE  " + value);
 });

I am getting test 2, to 4, tomorrow 1, today 2 which the counter is correct. However, it just does not sort in descending order. Any ideas?

Thanks!

Upvotes: 0

Views: 336

Answers (2)

user3392782
user3392782

Reputation: 181

I think you have been looking at "sortedTextSegmentList" which has the occurences in the order you are seeing them i.e. "test, to, today, tomorrow"

Try below :

LinkedHashMap sortedMap = sortedTextSegmentList.entrySet().stream()
         .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (x, y)-> {throw new AssertionError();}, LinkedHashMap::new
         ));

sortedMap should have the data in the order you are looking for.

Upvotes: 0

VeeArr
VeeArr

Reputation: 6178

While your use of LinkedHashMap should cause the result to maintain its ordering, you never actually assign the result of your collect operation to sortedTextSegmentList. As a result, your forEach is iterating over the first map you created, which is not sorted the way you want.

Upvotes: 1

Related Questions