【问题标题】:Matching objects in list based on id being same基于 id 匹配列表中的对象相同
【发布时间】:2022-10-01 09:09:31
【问题描述】:

我有清单一和清单二与一堆对象。我想从中删除项目清单一已经存在的清单二,但匹配必须仅基于ID,整个对象不必相同。如果 id 匹配,则必须从 listOne 中删除所述对象。请问我们如何使用 Java 流来实现这一点。

  • listOne.removeIf(o1 -> listTwo.stream().anyMatch(o2 -> o2.id == o1.id));
  • 或者如果 list2 很长,Set<IdType> idSet2 = list2.stream().map(i -> i.id).collect(toSet()); list1.removeIf(i -> idSet2.contains(i));。

标签: java


【解决方案1】:

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

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));
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-17
    相关资源
    最近更新 更多