Ebrin
Ebrin

Reputation: 209

Reversing sorting order of a stream using Comparator.reversed()

I'm writing a program that reads a string as an input and then outputs 10 most repeated words. Problem is, my order is reversed. I want to output from highest to lowest and it's sorted in opposite order. So I've been looking for a solution and only thing I found is .reversed() method but it says "Non-static method cannot be referenced from a static context". I don't understand this error, cause in the example it was used in a similar situation.

I'm new to streams so I'd like to know a simple way to resolve this issue.

public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String input = scanner.nextLine();
        List<String> words = Arrays.asList(input.split(" "));
        words.stream()
                .map(word -> word.replaceAll("[^A-Za-z0-9]", ""))
                .map(String::toLowerCase)
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .sorted(Comparator.comparing(Map.Entry::getValue).reversed()) // static method can't be referenced
                .limit(10)
                .sorted(Comparator.comparing(Map.Entry::getKey))
                .forEach(e -> System.out.println(e.getKey()));
    }

EDIT: I've had keys and values of a map mixed up and edited that. Due to my mistake, Arvind's answer might look a bit different, but it doesn't matter since Map.Entry has both .comparingByKey and .comparingByValue methods.

Upvotes: 3

Views: 1961

Answers (1)

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79580

Map.Entry.comparingByKey

You can pass Comparator.reverseOrder() to Map.Entry.comparingByKey.

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.function.Function;
import java.util.stream.Collectors;

class Main {
     public static void main(String[] args) {
         Scanner scanner = new Scanner(System.in);
         String input = scanner.nextLine();
         List<String> words = Arrays.asList(input.split(" "));
         words.stream()
                 .map(word -> word.replaceAll("[^A-Za-z0-9]", ""))
                 .map(String::toLowerCase)
                 .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                 .entrySet()
                 .stream()
                 .sorted(Map.Entry.comparingByKey(Comparator.reverseOrder())) 
                 .limit(10)
                 .sorted(Comparator.comparing(Map.Entry::getValue))
                 .forEach(e -> System.out.println(e.getKey()));
    }
}

A sample run:

1 2 3 4 5 6 7 8 9 1 2 5 9 2 7 2 3 9 5 3 1 8 3 6 8 2 3 6 9
4
7
8
6
5
1
9
3
2

Upvotes: 5

Related Questions