Java比较两个列表我有两个列表(不是java列表,可以说是两个列)例如**List 1** **Lists 2**
milan hafil
dingo iga
iga dingo
elpha binga
hafil mike
meat dingo
milan
elpha
meat
iga
neeta.peeta我想要一个返回多少元素是相同的方法。对于这个例子,它应该是3,并且应该返回列表和不同值的相似值。我应该使用hashmap,如果是,那么如何获得我的结果?请帮忙这不是学校的作业:)所以,如果你能指导我,那就足够了
3 回答
SMILET
TA贡献1796条经验 获得超4个赞
intersection()
subtract()
CollectionUtils
.
intersection()
subtract()
白板的微信
TA贡献1883条经验 获得超3个赞
java.util.HashSet<E>
retainAll
.
List<String> list1 = Arrays.asList( "milan", "milan", "iga", "dingo", "milan" ); List<String> list2 = Arrays.asList( "hafil", "milan", "dingo", "meat" ); // intersection as set Set<String> intersect = new HashSet<String>(list1); intersect.retainAll(list2); System.out.println(intersect.size()); // prints "2" System.out.println(intersect); // prints "[milan, dingo]" // intersection/union as list List<String> intersectList = new ArrayList<String>(); intersectList.addAll(list1); intersectList.addAll(list2); intersectList.retainAll(intersect); System.out.println(intersectList); // prints "[milan, milan, dingo, milan, milan, dingo]" // original lists are structurally unmodified System.out.println(list1); // prints "[milan, milan, iga, dingo, milan]" System.out.println(list2); // prints "[hafil, milan, dingo, meat]"
添加回答
举报
0/150
提交
取消