Pra Do
Pra Do

Reputation: 293

How to group by objects in java using collections?

I'm very new to Java and I am trying to group by objects based on the number but I'm unable to make it. Here is the example:

SomeCollection<Integer,String> t=new SomeCollection<Integer,String>();
t.put("1","a");
t.put("1","b");
t.put("2","c");

output:
1 - a,b
2 - c

Basically, when numbers are same then value needs to be grouped under that same number. It's all about asking how to perform this kind of strategical output to achieve by using any collections. Any help is appreciated.

Upvotes: 3

Views: 2639

Answers (3)

Kiran Patil
Kiran Patil

Reputation: 11

    Map<String, Integer> map = new HashMap<>();
    map.put("a", 1);
    map.put("b", 1);
    map.put("c", 2);
    map.put("d", 1);
    map.put("e", 3);
    map.put("f", 3);
    map.put("g", 3);

    //Using Java 7
    Set<Integer> set = new HashSet<Integer>();
    Map<Integer, List<String>> finalList = new HashMap<Integer, List<String>>();
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        set.add(entry.getValue());
        finalList.put(entry.getValue(), new ArrayList<String>());
    }
    for (Map.Entry<String, Integer> entry : map.entrySet()) {
        for (Integer value : set) {
            if (value.equals(entry.getValue())) {
                List<String> values = finalList.get(value);
                values.add(entry.getKey());
            }
        }
    }
    System.out.println("Result : " + finalList.toString());

Upvotes: 1

Peter Lawrey
Peter Lawrey

Reputation: 533530

There is even a construct which will help you do this.

Map<String, Integer> map = new HashMap<>();
map.put("a", 1);
map.put("b", 1);
map.put("c", 2);

Map<Integer, List<String>> groupedMap = map.keySet().stream()
        .collect(Collectors.groupingBy(map::get));

Upvotes: 0

Stepan Vavra
Stepan Vavra

Reputation: 4044

As suggested by others, you can use a Map<Integer, List<Object>> if you want to stick only to JDK collections.

However, there are Multi Value Maps out there which will do all the work for you for free. Check out this question what java collection that provides multiple values for the same key (see the listing here https://stackoverflow.com/a/22234446/3114959 in particular).

Upvotes: 3

Related Questions