Java Streams: Organize a collection into a map and select smallest key

Viewed 469

I'm pretty sure this is not possible in one line, but I just wanted to check:

List<WidgetItem> selectedItems = null;
Map<Integer, List<WidgetItem>> itemsByStockAvailable = WidgetItems.stream()
     .collect(Collectors.groupingBy(WidgetItem::getAvailableStock));
selectedItems = itemsByStockAvailable.get(
     itemsByStockAvailable.keySet().stream().sorted().findFirst().get());

Basically I'm collecting all widget items into a map where the key is the availableStock quantity and the value is a list of all widgets that have that quantity (since multiple widgets might have the same value). Once I have that map, I would want to select the map's value that corresponds to the smallest key. The intermediate step of creating a Map isn't necessary, it's just the only way I could think of to do this.

5 Answers
Related