-2

This is a repost of my previous post that i closed accidently

I have a LinkedHashMap like this : LinkedHashMap<String, HashMap<String, Double>> and I want to sort all elemens text1, text2, etc.... from the first HashMap by the value amount, in descending order.

This is what my HashMap look like :

{
    text1={
        amount=4847828.0,
        profit=1.6000000000000014
    },
    text2={
        amount=5353757.0, 
        profit=0.7000000000000002
    },
    text3={
        amount=1228950.0,
        profit=11.499999999999996
    },
    text4={
        amount=1446801.0,
        profit=0.2999999999999998
    },
    // long list of 208 elemens
}

Is there an "easy" way to do this ?

I found a similar post :Sorting LinkedHashMap But i can't figure how to do the same with a LinkedHashMap inside an another LinkedHashMap.

From my previous post I got this response, but I get java.lang.NullPointerException every time :

map.entrySet().stream()
        .sorted(Comparator.comparingDouble(entry -> entry.getValue().get("amount")))
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
SkyNalix
  • 57
  • 7

2 Answers2

0

Nevermind, the line at the bottom actually worked I just forgot to somewhere turn a HashMap to LinkedHashMap

The line :

map.entrySet().stream()
    .sorted(Comparator.comparingDouble(entry -> entry.getValue().get("amount")))
    .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> a, LinkedHashMap::new));
SkyNalix
  • 57
  • 7
0

This should work.

map.entrySet().stream()
        .sorted(Comparator.comparing(e->e.getValue().get("amount")))
            .collect(Collectors.toMap(Entry::getKey,Entry::getValue,
                        (a,b)->b,
                        LinkedHashMap::new
                        ));
WJS
  • 36,363
  • 4
  • 24
  • 39