Uploaded image for project: 'Commons Collections'
  1. Commons Collections
  2. COLLECTIONS-529

Add removeAll(Collection<E> collection, Collection<E> remove, Comparator<E> comparator) and contains(Collection<E> collection, E object, Comparator<E> comparator) methods

    XMLWordPrintableJSON

    Details

    • Type: Improvement
    • Status: Closed
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: None
    • Fix Version/s: 4.1
    • Component/s: Collection
    • Labels:
      None

      Description

      Hi,

      this request originates from one of our project where we have implemented something similar.

      The Java-Interface java.util.Collection<E> specifies the two methods contains(Object o) and boolean removeAll(Collection<?> c). Both methods rely on the equals() method of the given Objects.

      In some cases, it's not possible to change those methods and therefore removeAll and contains cannot be used directly.

      E.g. if you have an class myClass with property A and B and the equals method uses both properties, but you are only interested in property B.

      To solve this problem, I'd like to propose the following extensions of CollectionsUtils:

      /**
       * Removes all elements of remove from the collection using the comparator instead of .equals()
       */
      public static <E> Collection<E> removeAll(final Collection<E> collection, final Collection<E> remove, Comparator<E> comparator);
      /**
       * Checks if the given collection contains the object using the comparator instead of .equals()
       */
      public static <E> boolean contains(final Collection<E> collection, final E object, Comparator<E> comparator);
      

      Both methods do basically the same as their native equivalient but use a comparator instead of equals().

      This allows the injection of any required compare value:

      final Collection<myClass> result = CollectionUtils.removeAll(base, sub, new Comparator<myClass>() {
      
            public int compare(myClass o1, myClass o2) {
              return o1.getB() == o2.getB();
            }
          });
      

      If you think those methods are a good idea (as proposed or changed according to any rules), please give me a short feedback and I'll offer an implementation as diff patch for review.

      Cheers,

      Alex

        Attachments

        1. COLLECTIONS-529.patch
          8 kB
          Alexander Muthmann
        2. COLLECTIONS-529_1.patch
          13 kB
          Dipanjan Laha

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                amuthmann Alexander Muthmann
              • Votes:
                0 Vote for this issue
                Watchers:
                2 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: