Karl
Karl

Reputation: 223

List of Map entries from map

I'm trying to get a (sorted by value) list of map entries from a Map. I tried this:

List<Pair<String, AtomicInteger>> expectedList = expectedMap.entrySet().stream()
            .sorted(Comparator.comparing(e -> -e.getValue().get()))
            .map(e -> new Pair<>(e.getKey(), e.getValue())).collect(Collectors.toList());

but if I try to substitute Pair with Map.Entry, it tells me that Map.Entry is abstract and cannot be instantiated. Is there a way to adapt this construct to get a list of entries instead of a list of pairs?

Upvotes: 0

Views: 698

Answers (2)

lexicore
lexicore

Reputation: 43651

I don't see why you need to map Map.Entry to something else if you need Map.Entry.

Here's my take. I've opted to first create a list of entries and then sort it. Also used mor of the built-in API to construct the comparator.

List<Map.Entry<String, AtomicInteger>> expectedList = 
    new ArrayList<>(expectedMap.entrySet());

Collections.sort(expectedList,
    Map.Entry.comparingByValue(
        Comparator.comparingInt(AtomicInteger::get).reversed());

Upvotes: 1

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

See the Javadoc for Map.Entry:

Interface Map.Entry

All Known Implementing Classes:
AbstractMap.SimpleEntry, AbstractMap.SimpleImmutableEntry

Pick one implementing class that suits your needs, for example

List<Entry<String, AtomicInteger>> expectedList = expectedMap.entrySet().stream()
            .sorted(Comparator.comparingInt(e -> -e.getValue().get()))
            .map(e -> new AbstractMap.SimpleEntry<>(e.getKey(), e.getValue()))
            .collect(Collectors.toList());

But you could also just remove the map and use the entries that entrySet() returns:

List<Entry<String, AtomicInteger>> expectedList = expectedMap.entrySet().stream()
            .sorted(Comparator.comparingInt(e -> -e.getValue().get()))
            .collect(Collectors.toList());

PS.: If you are comparing primitive data types, you should use the right method like comparingInt. This avoids unnecessary boxing.

Upvotes: 4

Related Questions