YoHaRo
YoHaRo

Reputation: 142

using java 8 to group list of object by object attribute of type list: JAVA

I have an Object like

public class User {

    private String id;
    private List<String> brands_ids;
}

and I have a list of User objects like: example data

[
  {
    "id": 1,
    "brands_ids": [
      10,
      20,
      30
    ]
  },
  {
    "id": 2,
    "brands_ids": [
      10,
      50
    ]
  },
  {
    "id": 3,
    "brands_ids": [
      10,
      80
    ]
  }
]

My Question is, How to Group this list to know in which objects the brand id appears, for example brand id=10 appears in all three objects, the brand id=30 only in one object

a result of a map with key=brand id and value = count would solve my issue something like this: {10:3},{20:1},{30,1},{50,1},{80,1}

Upvotes: 0

Views: 4091

Answers (1)

Vasile Razdalovschi
Vasile Razdalovschi

Reputation: 448

Take a look here and here

This code fragment create 3 users, like in your example.

    var users = Arrays.asList(
            new User("1", Arrays.asList("10", "20", "30")),
            new User("2", Arrays.asList("10", "50")),
            new User("3", Arrays.asList("10", "80")));

    Map<String, Long> result = users
            .stream()
            .flatMap(user -> user.getBrand_ids().stream())
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

    System.out.println(result);
    // Result is: {80=1, 50=1, 30=1, 20=1, 10=3}

Upvotes: 7

Related Questions