Classical set operations for java.util.Collection

前端 未结 4 1073
情歌与酒
情歌与酒 2020-11-28 04:43

Is there any built-in functionality for classical set operations on the java.util.Collection class? My specific implementation would be for ArrayList, but this sounds like s

相关标签:
4条回答
  • 2020-11-28 05:03

    Intersection is done with Collection.retainAll; subtraction with Collection.removeAll; union with Collection.addAll. In each case, as Set will act like a set and a List will act like a list.

    As mutable objects, they operate in place. You'll need to explicitly copy if you want to retain the original mutable object unmutated.

    0 讨论(0)
  • 2020-11-28 05:16

    Are you looking for java.util.Set interface (and its implementations HashSet and TreeSet (sorted))?
    The interface defines removeAll(Collection c) which looks like substract(), and retainAll(Collection c) which looks like intersection.

    0 讨论(0)
  • 2020-11-28 05:23

    I would recommend Google Guava. The Sets class seems to have exactly what you are looking for. 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.

    0 讨论(0)
  • 2020-11-28 05:24

    For mutable operations see accepted answer.

    For an imutable variant you can do this with java 8

    subtraction

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

    intersection

    set1
      .stream()
      .filter(item-> set2.contains(item))
      .collect(Collectors.toSet())
    
    0 讨论(0)
提交回复
热议问题