Java 8 stream and grouping of list
Asked Answered
R

2

11

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?

Rundlet answered 14/6, 2016 at 14:57 Comment(0)
P
19

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())
Pinafore answered 14/6, 2016 at 14:59 Comment(0)
P
2

Collectors -> groupingBy and mapping can be used to achieve the result.

List<Order> orders = Arrays.asList(
                new Order(10, "Order 12345"),
                new Order(20, "Order 12346"),
                new Order(10, "Order 12347"),
                new Order(30, "Order 12348"),
                new Order(20, "Order 12389"),
                new Order(20, "Order 12390")
        );

        Map<Integer, List<String>> orderList = orders.stream()
                .collect(Collectors.groupingBy(Order::getUserId,
                        Collectors.mapping(Order::getOrderId, Collectors.toList())));

        System.out.println(orderList);
    }

Output:

{20=[Order 12346, Order 12389, Order 12390], 10=[Order 12345, Order 12347], 30=[Order 12348]}
Padron answered 2/1 at 16:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.