0

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());
WILLIAM
  • 457
  • 5
  • 28
  • Does this answer your question? [Comparator.comparing for Map.Entry in Java 8](https://stackoverflow.com/questions/46904399/comparator-comparing-for-map-entry-in-java-8) – pringi Jul 15 '22 at 07:54
  • @pringi thanks, but no, it can't – WILLIAM Jul 15 '22 at 08:01
  • I think it would be easier and a more readable solution to transform your maps into objects such as a list of 'Grocery' objects, with a type+price, and store those as a list. I realise this doesn't answer your specific question, but your specific question arises from your modelling. Sorting a list of Grocery objects would then be trivial and readable – Brian Agnew Jul 15 '22 at 08:04

2 Answers2

1

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

Eritrean
  • 15,851
  • 3
  • 22
  • 28
0

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));
Vaibs
  • 1,546
  • 9
  • 31