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");
The output will be :
{1=[a, b, c, c], 2=[c]}
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);
}
}
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);
}
The output will become :
{1=[a, b, c], 2=[c]}
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)