4

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.

1
  • 1
    In addition to the below answer, you can also use sorted((Comparator.<Map.Entry<String, Long>, Long>comparing(Map.Entry::getValue)).reversed()) or better: sorted((Map.Entry.<String, Long>comparingByValue()).reversed()) Commented Mar 21, 2021 at 16:47

1 Answer 1

6

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 
Sign up to request clarification or add additional context in comments.

1 Comment

It’s worth noting why it works and the question’s code doesn’t. Type inference has limitations when it comes to chained method invocations whereas it works without problems for nested invocations.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.