An Interest In:
Web News this Week
- April 27, 2024
- April 26, 2024
- April 25, 2024
- April 24, 2024
- April 23, 2024
- April 22, 2024
- April 21, 2024
April 4, 2022 03:06 am GMT
Original Link: https://dev.to/mustabelmo/an-easy-way-to-group-objects-in-java-4aok
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");
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.
Original Link: https://dev.to/mustabelmo/an-easy-way-to-group-objects-in-java-4aok
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To