数组转集合
List<String> list=Arrays.asList("1","2");
注意转换出来的List为Arrays内部类集合,与常规的ArrayList有区别,比如常见的remove(e)等方法不可用。
如何转换为常规数组
List<String> list=new ArrayList<>(Arrays.asList("1","2"))
两个集合交集
交集说明:只取两个数组都存在的元素
DEMO 1
List<String> listA = new ArrayList<>(Arrays.asList("1","2","3")); List<String> listB = new ArrayList<>(Arrays.asList("2","3","5")); boolean isChanged=listB.retainAll(listA); System.out.println(isChanged); System.out.println(Arrays.toString(listB.toArray()))
输出结果:
["2","3"]
DEMO 2
List<String> listA = new ArrayList<>(Arrays.asList("1","2","3")); List<String> listC = new ArrayList<>(Arrays.asList("5","6")); listC.retainAll(listA); System.out.println(Arrays.toString(listC.toArray()))
输出结果:
[]
两个集合并集
并集说明:两个集合合并成一个(可以存在相同元素)
DEMO 1
List<String> listA = new ArrayList<>(Arrays.asList("1","2","3")); List<String> listB = new ArrayList<>(Arrays.asList("2","3","5")); listB.addAll(listA); System.out.println(Arrays.toString(listB.toArray()))
输出结果:
["1","2","3","2","3","5"]
DEMO 2
List<String> listA = new ArrayList<>(Arrays.asList("1","2","3")); List<String> listC = new ArrayList<>(Arrays.asList("5","6")); listC.addAll(listA); System.out.println(Arrays.toString(listC.toArray()))
输出结果:
["1","2","3","5","6"]
两个集合并集去重
两个集合合并,且删除重复元素
DEMO 1
List<String> listA = new ArrayList<>(Arrays.asList("1","2","3")); List<String> listB = new ArrayList<>(Arrays.asList("2","3","5")); listB.removeAll(listA); listB.addAll(listA); System.out.println(Arrays.toString(listB.toArray()))
输出结果:
["1","2","3","5"]
两个集合差集
集合差集说明:A集合删除B集合里面与A相同的元素,保留A集合有B集合没有的部分
DEMO 1
List<String> listA = new ArrayList<>(Arrays.asList("1","2","3")); List<String> listB = new ArrayList<>(Arrays.asList("2","3","5")); listB.removeAll(listA); System.out.println(Arrays.toString(listB.toArray()))
输出结果:
["5"]
DEMO 2
List<String> listA = new ArrayList<>(Arrays.asList("1","2","3")); List<String> listC = new ArrayList<>(Arrays.asList("5","6")); listC.removeAll(listA); System.out.println(Arrays.toString(listC.toArray()))
输出结果:
["5","6"]
原创文章,作者:Maggie-Hunter,如若转载,请注明出处:https://blog.ytso.com/243854.html