以下是两个 list 取重复的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public static void main(string[] args) { list<integer> list1 = new arraylist<integer>(); for ( int i = 0 ; i < 5 ; i++) { list1.add(i); } list<integer> list2 = new arraylist<integer>(); for ( int i = 2 ; i < 8 ; i++) { list2.add(i); } system.out.println( "list1的数据:" + list1); system.out.println( "list2的数据:" + list2); system.out.println( "交集为" + getrepetition(list1, list2)); } /** * 两个list取重复 * @param list1 * @param list2 * @return */ public static list<integer> getrepetition(list<integer> list1, list<integer> list2) { list<integer> result = new arraylist<integer>(); for (integer integer : list2) { //遍历list1 if (list1.contains(integer)) { //如果存在这个数 result.add(integer); //放进一个list里面,这个list就是交集 } } return result; } |
当类型为引用类型也是可以的,因为 list.contains 内部实现为 equals() , 所以两个 string 类型的 list 也是可以用这个方法的
总结
以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。如果你想了解更多相关内容请查看下面相关链接
原文链接:https://blog.csdn.net/moneyshi/article/details/48368485
查看更多关于两个List集合取相同重复数据的方法的详细内容...