I need to create a collection of unique collection in java. Could someone please suggest possible containers for the same.
I want to have something like List<List<int>> where each each of the list could repeat itself in terms of its contents.
For example if my current state of the parent list is say
[ [1,2,3], [3,4,5], [4,5,6] ] and if I intend to add another list say [3,4,5] to it, it should not be duplicated and should not be added.
contains() method of List will work with integers, floats etc, but I am not sure if it will be able to match lists.
Please suggest any other container which could help.
Thanks.
You'll probably be best off using Set<List<Integer>> instead of List<List<Integer>>.
The above applied to your example:
Set<List<Integer>> uniqueLists = new HashSet<>();
uniqueLists.add(Arrays.asList(1, 2, 3));
uniqueLists.add(Arrays.asList(3, 4, 5));
uniqueLists.add(Arrays.asList(4, 5, 6));
// Now, this won't be added:
uniqueLists.add(Arrays.asList(3, 4, 5));
Be careful when you put a collection inside a set, though. You should not change it again, after you have put it in the set.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With