Karl
Karl

Reputation: 223

Comparator issue in Java

I have a Map<String, AtomicInteger> map in Java that I am trying to sort according to value (and then print). I have found a way that seems quick enough which is to first make an array Object[] a = map.entrySet().toArray(); And then I try to sort it like so

Arrays.sort(a, Comparator.comparingInt((Object entry) -> entry.getValue().get()))

Or like so:

Arrays.sort(a, new Comparator() {
        public int compare(Object o1, Object o2) {
            return ((Map.Entry<String, AtomicInteger>) o2).getValue()
                    .compareTo(((Map.Entry<String, AtomicInteger>) o1).getValue());
        }
    })

Unfortunately both these syntaxes are slightly wrong. In the first case it does not recognise the function getValue(), in the seconds it's compareTo that doesn't work. Can someone suggest corrections to the syntax to make it work?

Upvotes: 2

Views: 184

Answers (2)

Daniel Pryden
Daniel Pryden

Reputation: 60997

Why extract into an array? Why not just use sorted() on the entries directly?

For example:

private static List<Map.Entry<String, AtomicInteger>> sortedEntries(
        Map<String, AtomicInteger> map) {
    return map.entrySet()
        .stream()
        .sorted(Comparator.comparingInt(entry -> entry.getValue().get()))
        .collect(Collectors.toList());
}

Upvotes: 1

GhostCat
GhostCat

Reputation: 140613

Here:

Arrays.sort(a, Comparator.comparingInt((Object entry) -> entry.getValue().get()))

You are declaring the parameter to be Object. But it isn't. It is an Entry. And surprise, the class Object doesn't have methods such as getValue()!

And you shouldn't need to give the type in the first place:

Arrays.sort(a, Comparator.comparingInt(e -> entry.getValue().get()))

should do.

And yes, I missed that: the first problem is that a should be an array of Entry values not a Object[].

Besides: use names that mean something. a means like ... nothing.

Upvotes: 2

Related Questions