user2130951
user2130951

Reputation: 2741

Sort map by key string (where key is actually an integer)

I am trying to sort a map to show in a dropdown. But I am not able to get any sorting done. This will return a new map. But not with the map sorted by the key as I would expect.

private Map<String, String> mapInstrumentIDs = new TreeMap<>();

Map<Object, Object> val = mapInstrumentIDs
                    .entrySet()
                    .stream()
                    .sorted(Map.Entry.comparingByKey())
                    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

I of course didn't think about that the key is actually an integer. This means sorting it as a string does not give me the expected result (as integer sort). Changing the key to Integer and converting the value will yield the expected result.

Upvotes: 1

Views: 1290

Answers (3)

Joop Eggen
Joop Eggen

Reputation: 109597

Normally one would make a copy as:

private SortedMap<String, String> mapInstrumentIDs = new TreeMap<>();
SortedMap<String, String> val = new TreeMap(mapInstrumentIDs);

If you want a copy with key type Comparable<?> and value type Object, you want to specify the initial map as TreeMap and cannot use the standard collectors:

SortedMap<Comparable, Object> val = mapInstrumentIDs
                .entrySet()
                .collect(TreeMap<Comparable, Object>::new,
                    (m, e) -> { m.put(e.getKey(), e.getValue()); return m; },
                    (m, m2) -> m.addAll(m2)
                );

Upvotes: 0

Ace
Ace

Reputation: 710

By default a TreeMap guarantees that its elements will be sorted in ascending key order.

Upvotes: 5

Misha
Misha

Reputation: 28153

You should collect the results into a Map implementation that retains the order of its entries. LinkedHashMap will do:

Map<String, String> sorted = mapInstrumentIDs.entrySet().stream()
    .sorted(Map.Entry.comparingByKey())
    .collect(toMap(
            Map.Entry::getKey, 
            Map.Entry::getValue, 
            (x,y)-> {throw new AssertionError();},
            LinkedHashMap::new
    ));

Upvotes: 3

Related Questions