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.
sorted((Comparator.<Map.Entry<String, Long>, Long>comparing(Map.Entry::getValue)).reversed())or better:sorted((Map.Entry.<String, Long>comparingByValue()).reversed())