[英]What kind of helper method would I need to find an intersection between two arraylists?! (recursion only)
[英]Find intersection between two ArrayLists
查找两个字符串数组列表的交集。
这是代码:
public ArrayList<String> intersection( ArrayList<String> AL1, ArrayList<String> AL2){
ArrayList<String> empty = new ArrayList<String>();
ArrayList<String> empty1 = new ArrayList<String>();
if (AL1.isEmpty()){
return AL1;
}
else{
String s = AL1.get(0);
if(AL2.contains(s))
empty.add(s);
empty1.addAll(AL1.subList(1, AL1.size()));
empty.addAll(intersection(empty1, AL2));
return empty;
}
}
我希望输出看起来像这样:例如,
[a, b, c] intersect [b, c, d, e] = [b, c]
上面的代码给了我这个输出,但是我想知道如何使这个代码更容易理解。
您可以这样编写,使其更易于理解:
/**
* Computes the intersection of two Lists of Strings, returning it as a new ArrayList of Strings
*
* @param list1 one of the Lists from which to compute an intersection
* @param list2 one of the Lists from which to compute an intersection
*
* @return a new ArrayList of Strings containing the intersection of list1 and list2
*/
public ArrayList<String> intersection( List<String> list1, List<String> list2) {
ArrayList<String> result = new ArrayList<String>(list1);
result.retainAll(list2);
return result;
}
Java集合已经通过retainAll
调用对此提供了支持。 交集发生在原处,而不是返回新集,这就是为什么要保留原始list1必须创建新的ArrayList的原因。 如果调用对象被修改,则retainAll
返回一个布尔值
ArrayList<String> list1 = new ArrayList<String>();
list1.add("A");
list1.add("B");
list1.add("C");
ArrayList<String> list2 = new ArrayList<String>();
list2.add("D");
list2.add("B");
list2.add("C");
ArrayList<String> intersection = new ArrayList<String>(list1);
intersection.retainAll(list2);
for(String s: intersection){
System.out.println(s);
}
输出:
B
C
public ArrayList<String> intersection( ArrayList<String> AL1, ArrayList<String> AL2){
ArrayList<String> returnArrayList = new ArrayList<String>();
for(String test : AL1)
{
if(!returnArrayList.contains(test))
{
if(AL2.contains(test))
{
returnArrayList.add(test);
}
}
}
return returnArrayList;
}
您可以使用循环而不是递归。
如果您对依赖项没问题,我建议您看一下Apache Commons集合( http://commons.apache.org/proper/commons-collections/release_4_0.html )。
对于您的特定用途,它将是CollectionUtils( https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html )的方法交叉点
您可以使用Apache Commons Collections ListUtils.intersection
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.