简体   繁体   中英

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?

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.

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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM