Java - Distinct List of Objects

后端 未结 9 904
不知归路
不知归路 2020-12-05 09:41

I have a list/collection of objects that may or may not have the same property values. What\'s the easiest way to get a distinct list of the objects with equal properties? I

相关标签:
9条回答
  • 2020-12-05 10:34

    Java 8:

    recipients = recipients.stream()
        .distinct()
        .collect(Collectors.toList());
    

    See java.util.stream.Stream#distinct.

    0 讨论(0)
  • 2020-12-05 10:36

    If you're using Eclipse Collections, you can use the method distinct().

    ListIterable<Integer> integers = Lists.mutable.with(1, 3, 1, 2, 2, 1);
    Assert.assertEquals(
        Lists.mutable.with(1, 3, 2),
        integers.distinct());
    

    The advantage of using distinct() instead of converting to a Set and then back to a List is that distinct() preserves the order of the original List, retaining the first occurrence of each element. It's implemented by using both a Set and a List.

    MutableSet<T> seenSoFar = Sets.mutable.with();
    int size = list.size();
    for (int i = 0; i < size; i++)
    {
        T item = list.get(i);
        if (seenSoFar.add(item))
        {
            targetCollection.add(item);
        }
    }
    return targetCollection;
    

    If you cannot convert your original List into an Eclipse Collections type, you can use ListAdapter to get the same API.

    MutableList<Integer> distinct = ListAdapter.adapt(integers).distinct();
    

    Note: I am a committer for Eclipse Collections.

    0 讨论(0)
  • 2020-12-05 10:38

    Actually lambdaj implements this feature through the selectDistinctArgument method

    http://lambdaj.googlecode.com/svn/trunk/html/apidocs/ch/lambdaj/Lambda.html#selectDistinctArgument(java.lang.Object,%20A)

    0 讨论(0)
提交回复
热议问题