Java-JAVA快速查找多个List中相同的元素
public List getSame(List list1, List list2, List list3) {
List sameList = new ArrayList();
for (int i = 0; i < list1.size(); i++) {
for (int m = 0; m < list2.size(); m++) {
if (list1.get(i).equals(list2.get(m))) {
for (int n = 0; n < list3.size(); n++) {
if (list1.get(i).equals(list3.get(n))) {
sameList.add(list1.get(i));
}
}
}
}
}
return sameList;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
把list的值放到set中,然后set求交集不就ok了吗?
import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.junit.Test;
public class TestXX {
final public <E> List<E> findSameElem(List<List<E>> lists) {
if(lists.size()==0)return Collections.emptyList();
List<E> firstList = lists.get(0);
List<E> tmpList = new ArrayList<>(lists.get(0));
for (int i=1;i<lists.size();i++) {
List<E> aList=lists.get(i);
tmpList.retainAll(aList);
}
return tmpList;
}
@Test
public void testListOfListVersion(){
String[] strs={"23","2312","342","3423","我是谁?", "dfadvav"};
String[] strs1={"23", "我是谁?","dfasd","342","dfadvav"};
String[] strs2={"23","dfasdfad","34d2","我是谁?","dfadvav"};
String[] strsResult={"23","我是谁?","dfadvav"};
List<List<String>> inputList=new ArrayList<>();
inputList.add(Arrays.asList(strs));
inputList.add(Arrays.asList(strs1));
inputList.add(Arrays.asList(strs2));
assertEquals(Arrays.asList(strsResult),
findSameElem(inputList));
}
@SafeVarargs
final public <E> List<E> findSameElem(List<E> firstList, List<E>... lists) {
List<E> tmpList = new ArrayList<>(firstList);
for (List<E> aList: lists) {
tmpList.retainAll(aList);
}
return tmpList;
}
@Test
public void testVarargsVersion(){
String[] strs={"23","2312","342","3423","我是谁?", "dfadvav"};
String[] strs1={"23", "我是谁?","dfasd","342","dfadvav"};
String[] strs2={"23","dfasdfad","34d2","我是谁?","dfadvav"};
String[] strsResult={"23","我是谁?","dfadvav"};
assertEquals(Arrays.asList(strsResult),
findSameElem(Arrays.asList(strs), Arrays.asList(strs1), Arrays.asList(strs2)));
}
}
Java1.7