In this example, we will be making grouping easy to use on Maps objects that contain collections as values.
For instance, we hava aMap
ofIntegers
, that has its values as anArrayList
ofStrings
:
Grouper<Integer,String>grouper=newArrayListGrouper<>();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 definedArrayListGrouper
class uses anArrayList
as its strategy.
We can always define a new Grouper that will use anotherGroupingStrateg
.
Let's change theArrayList
to aHashSet
, so that the elements become unique :
publicclassHashSetGrouper<K,V>extendsGrouper<K,V>{publicHashSetGrouper(){super(HashSet::new);}}
Testing it like :
@TestpublicvoidtestHashSetGrouper(){Grouper<Integer,String>grouper=newHashSetGrouper<>();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]}
The1
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)
For further actions, you may consider blocking this person and/orreporting abuse