如果不存在,java 8将ListB的所有元素合并到ListA中

Seb*_*mer 10 java collections java-8 java-stream

我需要将listB的所有元素合并到另一个列表listA中.

如果listA中已存在一个元素(基于自定义相等检查),我不想添加它.

我不想使用Set,我不想重写equals()和hashCode().

原因是,我不想在listA本身防止重复,我只想在listB中已经存在我认为相等的元素时才从listB合并.

我不想重写equals()和hashCode(),因为这意味着我需要确保,我在各种情况下对元素的equals()实现都有.然而,可能是listB中的元素未完全初始化,即它们可能会遗漏一个对象id,其中可能存在于listA的元素中.

我目前的方法涉及一个接口和一个实用功能:

public interface HasEqualityFunction<T> {

    public boolean hasEqualData(T other);
}

public class AppleVariety implements HasEqualityFunction<AppleVariety> {
    private String manufacturerName;
    private String varietyName;

    @Override
    public boolean hasEqualData(AppleVariety other) {
        return (this.manufacturerName.equals(other.getManufacturerName())
            && this.varietyName.equals(other.getVarietyName()));
    }

    // ... getter-Methods here
}


public class CollectionUtils {
    public static <T extends HasEqualityFunction> void merge(
        List<T> listA,
        List<T> listB) {
        if (listB.isEmpty()) {
            return;
        }
        Predicate<T> exists
            = (T x) -> {
                return listA.stream().noneMatch(
                        x::hasEqualData);
            };
        listA.addAll(listB.stream()
            .filter(exists)
            .collect(Collectors.toList())
        );
    }
}
Run Code Online (Sandbox Code Playgroud)

然后我会像这样使用它:

...
List<AppleVariety> appleVarietiesFromOnePlace = ... init here with some elements
List<AppleVariety> appleVarietiesFromAnotherPlace = ... init here with some elements
CollectionUtils.merge(appleVarietiesFromOnePlace, appleVarietiesFromAnotherPlace);
...
Run Code Online (Sandbox Code Playgroud)

在listA中获取我的新列表,其中所有元素都从B合并

这是一个好方法吗?是否有更好/更简单的方法来实现相同的目标?

Tun*_*aki 7

你想要这样的东西:

public static <T> void merge(List<T> listA, List<T> listB, BiPredicate<T, T> areEqual) {
    listA.addAll(listB.stream()
                      .filter(t -> listA.stream().noneMatch(u -> areEqual.test(t, u)))
                      .collect(Collectors.toList())
    );
}
Run Code Online (Sandbox Code Playgroud)

您不需要HasEqualityFunction界面.您可以重复使用BiPredicate以测试两个对象在逻辑上是否相等.

此代码仅根据给定的谓词过滤listB未包含的元素listA.它确实遍历了listA有多少元素listB.


另一种更好的性能实现方法是使用包装元素的包装类,并将equals谓词作为方法:

public static <T> void merge(List<T> listA, List<T> listB, BiPredicate<T, T> areEqual, ToIntFunction<T> hashFunction) {

    class Wrapper {
        final T wrapped;
        Wrapper(T wrapped) {
            this.wrapped = wrapped;
        }
        @Override
        public boolean equals(Object obj) {
            return areEqual.test(wrapped, ((Wrapper) obj).wrapped);
        }
        @Override
        public int hashCode() {
            return hashFunction.applyAsInt(wrapped);
        }
    }

    Set<Wrapper> wrapSet = listA.stream().map(Wrapper::new).collect(Collectors.toSet());

    listA.addAll(listB.stream()
                      .filter(t -> !wrapSet.contains(new Wrapper(t)))
                      .collect(Collectors.toList())
    );
}
Run Code Online (Sandbox Code Playgroud)

这首先包装Wrapper对象内的每个元素并将它们收集到一个对象中Set.然后,它过滤listB未包含在该集合中的元素.通过委托给定谓词来完成相等性测试.限制是我们还需要给予hashFunction正确实施hashCode.

示例代码为:

List<String> listA = new ArrayList<>(Arrays.asList("foo", "bar", "test"));
List<String> listB = new ArrayList<>(Arrays.asList("toto", "foobar"));
CollectionUtils.merge(listA, listB, (s1, s2) -> s1.length() == s2.length(), String::length);
System.out.println(listA);
Run Code Online (Sandbox Code Playgroud)