从两个集合中添加元素
如何添加两个集合中的元素?
If there's a set one (1, 3, 6, 8)
And a set two (2, 4, 6, 8)
我如何将这两个元素结合在一起?
Output should be (1, 2, 3, 4, 6, 8)
这是我尝试过的:
Set<Integer> one = new HashSet();
one.add(1);
one.add(3);
// and so on
Set<Integer> two = new HashSet();
two.add(2);
two.add(4);
// and so on
Set<Integer> newSet = new HashSet();
newSet.add(one);
newSet.add(two);
return newSet;
这不起作用,因为 add 方法仅适用于单个整数,而不适用于整数集合。有没有一种方法可以将两组添加在一起?
我也得把套装还回去。我该怎么做?
How can I add elements from two sets?
If there's a set one (1, 3, 6, 8)
And a set two (2, 4, 6, 8)
How do I the elements from those two together?
Output should be (1, 2, 3, 4, 6, 8)
Here's what I tried:
Set<Integer> one = new HashSet();
one.add(1);
one.add(3);
// and so on
Set<Integer> two = new HashSet();
two.add(2);
two.add(4);
// and so on
Set<Integer> newSet = new HashSet();
newSet.add(one);
newSet.add(two);
return newSet;
And this doesn't work, as the add method works only for a single integer, not a collection of integer. Is there a method where I can add two sets together?
I also have to return the set. How do I do that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
Set.addAll()
另外,您应该输入构造函数(如上所述)。
要将其变成一种方法,请尝试以下操作:
让我们疯狂一下...这是一种方法,它将采用扩展所需类型的任意数量的任何类型的集合,并将它们合并为一组:
或者 Java 8+:
Use
Set.addAll()
Also, you should type your constructors (as above).
To make this into a method, try this:
Let's go nuts... here's a method that will take any number of collections of any type that extends the desired type, and merges them into one set:
Or Java 8+:
你不想要一套。正如您所发现的,根据定义,它们没有重复的元素。您正在寻找一个Multiset(实际上,从外观上看是一个SortedMultiset),也称为Bag。 Java 没有开箱即用的实现,但有可用的开源实现,例如 Google 的。
编辑:此外,您想要执行
setOne.addAll(setTwo)
,而不是一次一个元素,如上所述,但这是第二个问题。You don't want a Set. As you have discovered, they do not have duplicate elements, by definition. You are looking for a Multiset (in fact, a SortedMultiset by the looks of it), also known as a Bag. Java doesn't have one out of the box, but there are open source implementations available, for example, Google's.
EDIT: Also, you want to do
setOne.addAll(setTwo)
, not one element at a time, as commented above, but that is the secondary problem.正如 Bohemian 提到的,最好的答案是使用 Set.addAll()。请记住,如果您不介意覆盖其中一个集合,则将一组直接添加到另一组会更有效(至少从开发人员时间的角度来看:P):
As Bohemian mentioned, the best answer is using Set.addAll(). Just keep in mind that, if you don't mind overwriting one of your sets, it's more efficient (at least from the point of view of the developer's time :P) to add one set directly to another set:
或者使用排序的 ArrayList:
Or alternately use a sorted ArrayList: