Java-比较两个具有共同值的字符串列表,并返回多少个相同项

我想比较两个列表,并检查它们是否有共同点。


例子


List<String> list1 = new ArrayList();

list1.add("id1");

list1.add("id2");

list1.add("id3");

list1.add("id10");


List<String> list2 = new ArrayList();

list2.add("id10");

list2.add("id20");

list2.add("id3");

list2.add("id30");

list2.add("id31");

并返回在最短和最佳的过程中有多少个项目具有相同的值。


慕田峪9158850
浏览 369回答 4
4回答

慕婉清6462132

一种方法是,将两个列表中的元素放入Set,检查是否set.size()与list1.size()+list2.size()diff将是重复元素的计数。

弑天下

试试这个 :ArrayList intersection = new ArrayList<>(list1);intersection.retainAll(list2);相交处将包含共同要素

慕尼黑5688855

使用以下代码:&nbsp; &nbsp; Set<String> set =&nbsp; new HashSet<>(list1);&nbsp; &nbsp; set.addAll(list2);&nbsp; &nbsp; System.out.println(((list1.size() + list2.size()) - set.size()));

Cats萌萌

我不知道这是否是最有效的方法,但我会做这样的事情:public static int getCommonValues() {&nbsp; &nbsp; int values = 0;&nbsp; &nbsp; if(list1 != null && list2 != null) {&nbsp; &nbsp; &nbsp; &nbsp; Iterator it = list1.iterator();&nbsp; &nbsp; &nbsp; &nbsp; while(it.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String value = it.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; Iterator it2 = list2.iterator();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; while(it2.hasNext()) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; String value2 = it2.next();&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if(value2 == value) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; values = values + 1;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; break;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return values;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java