class Solution {
public int[] intersection(int[] nums1, int[] nums2) {
Set<Integer> set = new HashSet<>();
for(int i = 0;i< nums1.length; i++){
set.add(nums1[i]);
}
Set<Integer> set2 = new HashSet<>();
for(int i = 0;i< nums2.length; i++){
set2.add(nums2[i]);
}
List<Integer> list = new ArrayList<>();
for(int e : set2){
if(set.contains(e)){
list.add(e);
}
}
int ret[] = new int[list.size()];
for(int i = 0; i< list.size(); i++){
ret[i] = list.get(i);
}
return ret;
}
}
set集合没有下标,set集合是无序的。
将更便捷地打印数组:
Stream.of(aaa).forEach(System.out::println);//只能打印String类型的数组
Arrays.asList(aaa).stream().forEach(s -> System.out.println(s));//只能打印String类型数组
Arrays.stream(aaa).forEach(System.out::println);//可以打印int型
将list集合转换为数组:
Object[] ans1 = l1.toArray(); //直接将 list 转换成 Object[] 类型的 数组;
Integer[] ans2 = (Integer[]) l1.toArray(new Integer[l1.size()]); //输出指定类型的数组,输出的数组类型与括号中参数类型一致;
if (nums1 == null || nums1.length == 0 || nums2 == null || nums2.length == 0) {
return new int[0];
}
Set<Integer> set1 = new HashSet<>();
Set<Integer> resSet = new HashSet<>();
//遍历数组1
for (int i : nums1) {
set1.add(i);
}
//遍历数组2的过程中判断哈希表中是否存在该元素
for (int i : nums2) {
if (set1.contains(i)) {
resSet.add(i);
}
}
//方法1:将结果集合转为数组
return resSet.stream().mapToInt(x -> x).toArray();
将Set集合转换为数组: