TheDonLUIS1
TheDonLUIS1

Reputation: 3

How can I sort a map with string key? like (1 foo , 2 foo)

'Im using hibernate, I was planing to use a LinkedHashMap to sort the elements, but it doesnt work because i couldn't initialize as that, so Im making the sort from the controller, so it works, but not as well, this my method to sort.

public LinkedHashMap<String, Indicador> OrdenarMap(Map<String, Indicador> map) {

        LinkedHashMap<String, Indicador> sortedMap = new LinkedHashMap<>();

        map.entrySet()
                .stream()
                .sorted(Map.Entry.comparingByKey())
                .forEachOrdered(x -> sortedMap.put(x.getKey(), x.getValue()));

        return sortedMap;
    }

These are my keys the sort its correct but...

I want the order like this

{1 Objetivo General, 1.1 Objetivo Especifico, 2 Objetivo General} etc....

Upvotes: 0

Views: 148

Answers (2)

Pier-Alexandre Bouchard
Pier-Alexandre Bouchard

Reputation: 5235

Use a TreeMap with a custom Comparator.

By default, the String Comparator compares Strings lexicographically and this is the reason why you see an order like this {"1", "10", "11", ..., "2", "20"}.

Because I assume your key will always be a double, this Comparator should work:

TreeMap<String, Indicador> sortedMap = new TreeMap<>(new Comparator<String>() {
    public int compare(String string1, String string2) {
        return Double.parseDouble(string1) - Double.parseDouble(string2) < 0.0 ? -1 : 1;
    }
});

Upvotes: 1

locus2k
locus2k

Reputation: 2935

Look at TreeMap. It sorts by the natural order of the keys

A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used.

https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html

The constructor also can take in a comparator for the keys to do your own sorting.

Upvotes: 1

Related Questions