[英]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.我需要在 java 中创建一个独特的集合。有人可以为相同的容器建议可能的容器。
I want to have something like List<List<int>>
where each each of the list could repeat itself in terms of its contents.我想要类似List<List<int>>
的东西,其中每个列表都可以根据其内容重复自身。
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.例如,如果我当前的父列表 state 是[ [1,2,3], [3,4,5], [4,5,6] ]
,如果我打算添加另一个列表,请说[3,4,5]
,它不应该被复制,也不应该被添加。
contains() method of List will work with integers, floats etc, but I am not sure if it will be able to match lists. List 的 contains() 方法适用于整数、浮点数等,但我不确定它是否能够匹配列表。
Please suggest any other container which could help.请建议任何其他可能有帮助的容器。
Thanks.谢谢。
You'll probably be best off using Set<List<Integer>>
instead of List<List<Integer>>
.您可能最好使用Set<List<Integer>>
而不是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.将它放入集合后,不应再次更改它。
Perhaps you would be interested to use Set<Set<Integer>>
.也许您会对使用Set<Set<Integer>>
感兴趣。
In case you would like to maintain the addition order, you can use LinkedHashSet
.如果您想维护添加顺序,可以使用LinkedHashSet
。
Your code will be like你的代码会像
Set<Set<Integer> uniqueLists = new LinkedHashSet<Set<Integer>>();
uniqueLists.add(new LinkedHashSet(Arrays.asList(1, 2, 3)));
It would avoid two problems from using Set<List<Integer>>
.它将避免使用Set<List<Integer>>
的两个问题。
1) It would retains addition order of the individual lists 1)它将保留单个列表的添加顺序
2) It individual list will also not have duplicate integer entries. 2)它的个人列表也不会有重复的 integer 条目。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.