DEV Community

Mustapha Belmokhtar
Mustapha Belmokhtar

Posted on

An easy way to group objects in java

In this example, we will be making grouping easy to use on Maps objects that contain collections as values.
For instance, we hava a Map of Integers, that has its values as an ArrayList of Strings :

Grouper<Integer, String> grouper = new ArrayListGrouper<>();
        grouper.put(1, "a");
        grouper.put(1, "b");
        grouper.put(1, "c");
        grouper.put(1, "c");
        grouper.put(2, "c");
Enter fullscreen mode Exit fullscreen mode

The output will be :

{1=[a, b, c, c], 2=[c]}
Enter fullscreen mode Exit fullscreen mode

All we have to do, is to define a grouping strategy, for example the already defined ArrayListGrouper class uses an ArrayList as its strategy.
We can always define a new Grouper that will use another
GroupingStrateg.

Let's change the ArrayList to a HashSet, so that the elements become unique :

public class HashSetGrouper<K, V> extends Grouper<K, V> {

    public HashSetGrouper() {
        super(HashSet::new);
    }
}
Enter fullscreen mode Exit fullscreen mode

Testing it like :

@Test
    public void testHashSetGrouper() {
        Grouper<Integer, String> grouper = new HashSetGrouper<>();
        grouper.put(1, "a");
        grouper.put(1, "b");
        grouper.put(1, "c");
        grouper.put(1, "c");
        grouper.put(2, "c");
        System.out.println(grouper);

    }
Enter fullscreen mode Exit fullscreen mode

The output will become :

{1=[a, b, c], 2=[c]}
Enter fullscreen mode Exit fullscreen mode

The 1 key has now a set in which the "c" value is not repeated.

the code is hosted on Github : https://github.com/BelmoMusta/java-Grouper
Your feedback is welcomed.

Top comments (0)