Reputation: 43
Find intersection of two ArrayLists of Strings.
Here is the code:
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;
}
}
I want the output to look like this: For example,
[a, b, c] intersect [b, c, d, e] = [b, c]
The above code give me this output, but I want to know how to make this code more easier to understand.
Upvotes: 0
Views: 12245
Reputation: 531
You can use Apache Commons Collections ListUtils.intersection
http://commons.apache.org/proper/commons-collections/javadocs/api-2.1.1/org/apache/commons/collections/ListUtils.html#intersection(java.util.List, java.util.List)
Upvotes: 0
Reputation: 174
If you are ok with a dependency, i would recommend you to take a look at apache commons collections (http://commons.apache.org/proper/commons-collections/release_4_0.html).
For your specific use it would be the method intersection from CollectionUtils (https://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/CollectionUtils.html)
Upvotes: 0
Reputation: 8724
Java collections already have support for this with the retainAll
call. Rather than return a new set, the intersection happens in place, which is why you must create a new ArrayList if you want to retain the original list1. retainAll
returns a boolean if the calling object is modified
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);
}
Output:
B
C
Upvotes: 1
Reputation: 13222
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;
}
You could use loops instead of recursion.
Upvotes: 0
Reputation: 180181
You could make it easier to understand by writing it like this:
/**
* 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;
}
Upvotes: 3