0

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}

1
  • I'm confused. Do you just want to count them or do you want a way to ask what id's have which brands? If you have tried to group them from iterating over a list of User objects, please share the code. Commented Feb 4, 2020 at 20:34

1 Answer 1

7

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}
Sign up to request clarification or add additional context in comments.

2 Comments

If you use java 8, just change FROM: 'var users' TO 'List<User> users'
hi @vas, i wonder how to make result as list ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.