I have the following Item class:
@AllArgsConstructor
@Getter
public static class Item {
public enum Type { Meat, Fish }
private String name;
private int price;
private Type type;
}
And there's a List of items like shown below:
List<Item> menu = Arrays.asList(
new Item("pork" 800, Item.Type.Meat),
new Item("beef" 700, Item.Type.Meat),
new Item("chicken", 200, Item.Type.meat),
new Item("prawns" 300, Item.Type.Fish),
new Item("salmon", 450, Item.Type.Fish)
);
I need to group Item by Type and store into a map.
And then I need to sort map entries by Value (which in this case is a List of Strings) in ascending order and store into a LinkedHashMap.
How do I sort a map entries based on a List<String> value?
My code:
// grouping items by type
Map<Item.Type, List<String>> map = menu.stream()
.collect(Collectors.groupingBy(
Item:: getType,
Collectors.mapping(Item::getName, Collectors.toList())
));
// a LinkedHashMap to store sorted entries
Map<Item.Type, List<String>> hmap = new LinkedHashMap<>();
// attempting to sort map entries by value and put them
// into the resulting map
map.entrySet().stream()
.sorted(Map.Entry.<Item.Type, List<String>> comparingByValue())
.forEachOrdered(e -> hmap.put(e.getKey(), e.getValue()));
But I'm getting a compilation error:
Type parameter 'java.util.List' is not within its bound;
should extend 'java.lang.Comparable<? super java.util.List>'
I think the reason is because I have a list of String in a map which I want to sort.
When I have just a String as a value (Not List<String>). The code works perfectly well.