俩个数组去重合并成一个数组

it2022-06-22  74

import java.util.*; public class Merge { public static void main(String[] args) { int [] a = {1, 2, 7, 4, 4, 2}; int [] b = {1, 5, 5, 6}; int [] c = concat(a, b); setDistinct(c); listDistinct(c); mapDistinct(c); } //合并数组 public static int[] concat(int [] first, int[] second) { int [] result = Arrays.copyOf(first, first.length + second.length); System.arraycopy(second, 0, result, first.length, second.length); return result; } //数组去重 //第一种:使用set集合无序不重复 public static void setDistinct(int[] arr) { HashSet<Integer> set = new HashSet<Integer>(); for (Integer i : arr) { set.add(i); } Integer[] newArr = set.toArray(new Integer[1]); System.out.println(Arrays.toString(newArr)); } //第二种:使用list集合,判断元素不存在再插入 public static void listDistinct(int [] arr) { List<Integer> list = new ArrayList<Integer>(); for (int i = 0; i < arr.length; i++) { if (!list.contains(arr[i])) { list.add(arr[i]); } } Integer[] newArrStr = list.toArray(new Integer[1]); System.out.println(Arrays.toString(newArrStr)); } //第三种:使用Map集合,键唯一 public static void mapDistinct(int [] arr) { Map<Integer, Object> map = new HashMap<Integer, Object>(); for (Integer i : arr) { map.put(i, i); } Integer[] newArrStr = map.keySet().toArray(new Integer[1]); System.out.println(Arrays.toString(newArrStr)); } }

最新回复(0)