Home > OS >  How to sort Hashmap<String, Map<String, Double>> in Java?
How to sort Hashmap<String, Map<String, Double>> in Java?

Time:07-16

I know in Java8, it provided the below way to sort dictionary. But how about dictionary in dictionary? How can I pass the field I wanna compare in .sorted()? Or I should use another object type to hold the data? Thanks

Here's the sample dictionary and I wish to sort by todayPrice:

{
  Apple={
    todayPrice=10,
    ytdClose=20,
    Quantity=30.0
  },
  Orange={
    todayPrice=3,
    ytdClose=5,
    Quantity=20.0
  },
  Cake={
    todayPrice=87,
    ytdClose=55,
    Quantity=3.0
  }
}

Sort one dictionary:

Stream<Map.Entry<K,V>> sorted =
    map.entrySet().stream()
       .sorted(Map.Entry.comparingByValue());

CodePudding user response:

You can use a custom Comparator:

Map<String, Map<String, Double>> input = Map.of(
    "Apple",  Map.of("todayPrice", 10., "ytdClose", 20., "Quantity", 30.0),
    "Orange", Map.of("todayPrice",  3., "ytdClose",  5., "Quantity", 20.0),
    "Cake",   Map.of("todayPrice", 87., "ytdClose", 55., "Quantity",  3.0));

Comparator<Entry<String,Map<String,Double>>> byTodaysPrice = 
     Comparator.comparingDouble(e -> e.getValue().get("todayPrice"));

Map<String, Map<String, Double>> out = input
        .entrySet()
        .stream()
        .sorted(byTodaysPrice)
        .collect(Collectors.toMap(
                 Entry::getKey, Entry::getValue, (a,b) -> a, LinkedHashMap::new));

System.out.println(out);

use ...sorted(byTodaysPrice.reversed()).... to sort descending

CodePudding user response:

try below::

Map<String, FruitsDetails> sortedMap = map.entrySet().stream()
        .sorted(Map.Entry.comparingByValue(Comparator.comparing(FruitsDetails::getTodayPrice))).collect(Collectors.toMap(
                Map.Entry::getKey, Map.Entry::getValue, (oldValue, newValue) -> oldValue, LinkedHashMap::new));
  • Related