Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

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 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");
Enter fullscreen modeExit fullscreen mode

The output will be :

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

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 another
GroupingStrateg.

Let's change theArrayList to aHashSet, so that the elements become unique :

publicclassHashSetGrouper<K,V>extendsGrouper<K,V>{publicHashSetGrouper(){super(HashSet::new);}}
Enter fullscreen modeExit fullscreen mode

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);}
Enter fullscreen modeExit fullscreen mode

The output will become :

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

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)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Java developer since 2011
  • Location
    Oujda-Morocco
  • Joined

More fromMustapha Belmokhtar

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp