如何优雅查找两个存储自定义对象的ArrayList中各自独有的字符串
Java自定义对象ArrayList差异字符串查询优化方案
核心优化思路
- 提前抽取两个列表的目标字符串属性存入
HashSet,利用Set O(1)时间复杂度的查找能力,将原实现O(n*m)的时间复杂度降低为O(n+m),数据量越大性能提升越明显 - 逻辑清晰简洁,无需重复编写反向比对的遍历代码
优化后代码
import java.util.ArrayList; import java.util.Set; import java.util.stream.Collectors; public class CompareTwoArrays { ArrayList<MyCustomObject> firstArrayListOfObjects = new ArrayList<>(); ArrayList<MyCustomObject> secondArrayListOfObjects = new ArrayList<>(); public void superSpecificExampleMethod() { firstArrayListOfObjects.add(new MyCustomObject(1, 1, "apple")); firstArrayListOfObjects.add(new MyCustomObject(1, 1, "orange")); firstArrayListOfObjects.add(new MyCustomObject(1, 1, "banana")); firstArrayListOfObjects.add(new MyCustomObject(1, 1, "grape")); secondArrayListOfObjects.add(new MyCustomObject(1, 1, "apple")); secondArrayListOfObjects.add(new MyCustomObject(1, 1, "pineapple")); secondArrayListOfObjects.add(new MyCustomObject(1, 1, "orange")); secondArrayListOfObjects.add(new MyCustomObject(1, 1, "banana")); // 提前提取两个列表的字符串属性生成Set,用于快速查找 Set<String> firstStrSet = firstArrayListOfObjects.stream() .map(MyCustomObject::getString) .collect(Collectors.toSet()); Set<String> secondStrSet = secondArrayListOfObjects.stream() .map(MyCustomObject::getString) .collect(Collectors.toSet()); // 查找仅存在于第一个列表的字符串 firstArrayListOfObjects.stream() .map(MyCustomObject::getString) .filter(str -> !secondStrSet.contains(str)) .forEach(str -> System.out.println(str + " doesn't exist in second arrayList")); // 查找仅存在于第二个列表的字符串 secondArrayListOfObjects.stream() .map(MyCustomObject::getString) .filter(str -> !firstStrSet.contains(str)) .forEach(str -> System.out.println(str + " doesn't exist in first arrayList")); } } class MyCustomObject { private int randomIntOne; private int randomIntTwo; private String string; public MyCustomObject(int randomIntOne, int randomIntTwo, String string) { this.randomIntOne = randomIntOne; this.randomIntTwo = randomIntTwo; this.string = string; } public String getString() { return string; } }
场景适配
如果只需要获取无重复的差异字符串集合,可以直接用Set求差集,代码更精简:
// 仅在第一个列表存在的字符串(无重复) Set<String> onlyInFirst = new HashSet<>(firstStrSet); onlyInFirst.removeAll(secondStrSet); // 仅在第二个列表存在的字符串(无重复) Set<String> onlyInSecond = new HashSet<>(secondStrSet); onlyInSecond.removeAll(firstStrSet);
内容的提问来源于stack exchange,提问作者Apple
相关产品推荐
相关产品推荐

