0

'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....

Wojciech Wirzbicki
  • 3,887
  • 6
  • 36
  • 59
  • Use a comparator for the version strings, instead of just `Map.Entry.comparingByKey()`. See this question for example: https://stackoverflow.com/questions/6701948/efficient-way-to-compare-version-strings-in-java – Alex Shesterov Dec 13 '18 at 16:16
  • @TheDonLUIS1: What are the actual keys you're trying to sort by? (Please put them in the text of the question, not as an image of text.) What order are you getting, and what order do you want to get? I think Alex Shesterov is on the right track, and you probably are in fact getting a "correctly" ordered output, but you simply want a *different* order -- which means you're probably going to want to write a `Comparator` that expresses the ordering you intend. – Daniel Pryden Dec 13 '18 at 16:19
  • my keys are {1 Objetivo General, 2 Objetivo General, 3 Objetivo General, 1.1 Objetivo Especifico, .........N Objetivo General } so the sort make this,{ 1 Objetivo General, 10 Objetivo General, 11 Objetivo .............2 Objetivo General}, the order i want is this {1 Objetivo General, 1.1 Objetivo, 1.2, 2, 2.2, 2.3, 3...} etc. Thanks for your time – TheDonLUIS1 Dec 13 '18 at 16:22

2 Answers2

1

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.

locus2k
  • 2,802
  • 1
  • 14
  • 21
1

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;
    }
});
Pier-Alexandre Bouchard
  • 5,135
  • 5
  • 37
  • 72