时间复杂度:O( nlog(n) )
输出结果集为Collection子类:如图
/**
* 获取两个字符串List的相同元素
*
* @param listOne 字符串列表1
* @param listTwo 字符串列表2
* @param result 用于装结果集的容器
* @return 返回两个字符串List的相同元素
*/
private static <T extends Collection<String>> T getAllSameElementOnTwoList(List<String> listOne, List<String> listTwo, T result) {
if (listOne.isEmpty() || listTwo.isEmpty()) {
return result;
}
Collections.sort(listOne);
Collections.sort(listTwo);
int k = 0;
int j = 0;
while (k < listOne.size() && j < listTwo.size()) {
if (listOne.get(k).compareTo(listTwo.get(j)) == 0) {
if (listOne.get(k).equals(listTwo.get(j))) {
result.add(listOne.get(k));
k++;
j++;
}
} else if (listOne.get(k).compareTo(listTwo.get(j)) < 0) {
k++;
} else {
j++;
}
}
return result;
}
示例:容器为HashSet,对相同的元素进行去重。
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("ab");
list1.add("abc");
list1.add("ab");
list1.add("abcd");
list1.add("a");
list2.add("d");
list2.add("abc");
list2.add("abcd");
//获取当前时间戳
long last = System.currentTimeMillis();
for (String value : Objects.requireNonNull(getAllSameElementOnTwoList(list1, list2, new HashSet<>()))) {
System.out.print(value + " ");
}
System.out.println();
long now = System.currentTimeMillis();
System.out.println(now - last);
}
//abc abcd
}
方法二,使用List接口的retainAll来取交集
/**
* Retains only the elements in this list that are contained in the
* specified collection (optional operation). In other words, removes
* from this list all of its elements that are not contained in the
* specified collection.
*
* @param c collection containing elements to be retained in this list
* @return true if this list changed as a result of the call
* @throws UnsupportedOperationException if the retainAll operation
* is not supported by this list
* @throws ClassCastException if the class of an element of this list
* is incompatible with the specified collection
* (optional)
* @throws NullPointerException if this list contains a null element and the
* specified collection does not permit null elements
* (optional),
* or if the specified collection is null
* @see #remove(Object)
* @see #contains(Object)
*/
boolean retainAll(Collection<?> c);
使用案例:
public static void main(String[] args) {
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
list1.add("ab");
list1.add("abc");
list1.add("ab");
list1.add("abcd");
list1.add("a");
list2.add("d");
list2.add("abc");
list2.add("abcd");
list1.retainAll(list2);
System.out.println(list1);
}
//[abc, abcd]
}
如果需要改变原list的可以用方法二,不想改原list结构的话可以使用方法一。