根据ID相同匹配列表中的对象

wbrvyc0a  于 2022-10-01  发布在  Java
关注(0)|答案(1)|浏览(256)

我有listOnelistTwo,其中有一堆对象。我想从listOne中删除listTwo中已经存在的项,但匹配只能基于id,整个对象不需要相同。如果id匹配,则必须将所述对象从listOne中移除。请问我们如何使用Java Streams来实现这一点。

wgeznvg7

wgeznvg71#

这些单子的大致大小是多少?通过扫描ListTwo并制作一组ID(例如使用listOne.removeIf(thing -> idsFromListTwo.contains(thing.id)))进行预处理可能是有意义的。集合中的查找将比列表的顺序扫描更快。

package example.stackoverflow;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class ListFilter {
    static record Thing(String id, Object data){};
    public static void main(String[] args) {
        int n = 100;
        int m = 10;
        List<Thing> listOne = makeListOfThings(n-m, n*2-m);
        List<Thing> listTwo = makeListOfThings(0, n);

        System.out.println("listOne: "+listOne);
        System.out.println("listTwo: "+listTwo);

        Collections.shuffle(listOne);
        Collections.shuffle(listTwo);

        System.out.println("After suffling...");
        System.out.println("listOne: "+listOne);
        System.out.println("listTwo: "+listTwo);

        List<Thing> copyOfOne = new ArrayList<>(listOne);

        long before = System.nanoTime();
        var idsTwo = listTwo.stream().map(Thing::id)
                .collect(Collectors.toSet());
        listOne.removeIf(t -> idsTwo.contains(t.id));
        long after = System.nanoTime();
        System.out.println("After removing things that were also in listTwo...");
        System.out.println("listOne (after): "+listOne);
        System.out.println("           Size: "+listOne.size());
        System.out.println("Time taken: "+((after-before)/1000.0)+" microseconds");

        System.out.println("Without using a Set...");
        before = System.nanoTime();
        copyOfOne.removeIf(t1 -> listTwo.stream().anyMatch(t2 -> t2.id.equals(t1.id)));
        after = System.nanoTime();
        System.out.println("listOne (after): "+copyOfOne);
        System.out.println("           Size: "+copyOfOne.size());
        System.out.println("Time taken: "+((after-before)/1000.0)+" microseconds");
    }

    static List<Thing> makeListOfThings(int startingID, int endingID) {
        return IntStream.range(startingID, endingID)
                .mapToObj(i -> new Thing(String.valueOf(i), Objects.hash(i,System.nanoTime())))
                .collect(Collectors.toCollection(ArrayList::new));
    }
}

相关问题