Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 stream and grouping of list

I have a list of orders and I want to group them by user using Java 8 stream and Collectors.groupingBy:

orderList.stream().collect(Collectors.groupingBy(order -> order.getUser())

This return a map containing users and the list of orders:

Map<User, List<Order>>

I don't need the entire object User just a field of it username which is a String, so I want to get something like this:

Map<String, List<Order>>

I tried to map the User to the username field using Stream.map but can't get it right. How can I do this as simply as possible?

like image 258
Jones Avatar asked Dec 11 '22 16:12

Jones


1 Answers

You can just use the groupingBy collector with the username instead of the whole User object:

orderList.stream().collect(Collectors.groupingBy(order -> order.getUser().getUsername())
like image 65
Leon Avatar answered Mar 06 '23 23:03

Leon