Java-JAVA快速查找多个List中相同的元素

发布于 2016-12-07 09:49:21 字数 687 浏览 1567 评论 2

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

虐人心 2017-08-14 11:41:48

把list的值放到set中,然后set求交集不就ok了吗?

偏爱自由 2017-03-01 23:15:39

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文