简体   繁体   English

java.util.Collection的经典集合操作

[英]Classical set operations for java.util.Collection

Is there any built-in functionality for classical set operations on the java.util.Collection class? java.util.Collection类上的经典集合操作是否有任何内置功能? My specific implementation would be for ArrayList, but this sounds like something that should apply for all subclasses of Collection. 我的具体实现将是ArrayList,但这听起来应该适用于Collection的所有子类。 I'm looking for something like: 我正在寻找类似的东西:

ArrayList<Integer> setA ...
ArrayList<Integer> setB ...
ArrayList<Integer> setAintersectionB = setA.intersection(setB);
ArrayList<Integer> setAminusB = setA.subtract(setB);

After some searching, I was only able to find home-grown solutions. 经过一番搜索,我才能找到本土解决方案。 Also, I realize I may be confusing the idea of a "Set" with the idea of a "Collection", not allowing and allowing duplicates respectively. 此外,我意识到我可能会混淆“集合”的想法与“集合”的想法混淆,不允许和分别允许重复。 Perhaps this is really just functionality for the Set interface? 也许这只是Set界面的功能?

In the event that nobody knows of any built-in functionality, perhaps we could use this as a repository for standard practice Java set operation code? 如果没有人知道任何内置功能,也许我们可以将其用作标准实践Java集操作代码的存储库? I imagine this wheel has been reinvented numerous times. 我想这个轮子已经多次重新发明。

Intersection is done with Collection.retainAll ; 交叉点用Collection.retainAll完成; subtraction with Collection.removeAll ; 使用Collection.removeAll减法; union with Collection.addAll . Collection.addAll联合。 In each case, as Set will act like a set and a List will act like a list. 在每种情况下, Set将像一个集合, List将像列表一样。

As mutable objects, they operate in place. 作为可变对象,它们在适当的位置运行。 You'll need to explicitly copy if you want to retain the original mutable object unmutated. 如果要保留原始可变对象未突变,则需要显式复制。

I would recommend Google Guava . 我会推荐谷歌番石榴 The Sets class seems to have exactly what you are looking for. Sets类似乎正是您正在寻找的。 It has a intersection method and a difference method. 它有交叉方法和差分方法。

This presentation is probably something you want to watch if you're interested. 如果您有兴趣,可能需要观看此演示文稿 It refers to Google Collections, which was Guava's original name. 它指的是Google Collections,这是Guava的原始名称。

Are you looking for java.util.Set interface (and its implementations HashSet and TreeSet (sorted))? 您在寻找java.util.Set接口(及其实现HashSet和TreeSet(已排序))?
The interface defines removeAll(Collection c) which looks like substract(), and retainAll(Collection c) which looks like intersection. 接口定义了removeAll(Collection c),它看起来像substract(),而retainAll(Collection c)看起来像是交集。

For mutable operations see accepted answer. 对于可变操作,请参阅接受的答案。

For an imutable variant you can do this with java 8 对于一个可重定义的变体,您可以使用java 8执行此操作

subtraction 减法

set1
  .stream()
  .filter(item-> !set2.contains(item))
  .collect(Collectors.toSet())

intersection 路口

set1
  .stream()
  .filter(item-> set2.contains(item))
  .collect(Collectors.toSet())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM