Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List of unique lists in java

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.

like image 405
user1317105 Avatar asked Nov 25 '25 03:11

user1317105


1 Answers

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.

like image 63
Lukas Eder Avatar answered Nov 26 '25 17:11

Lukas Eder