java-两种方法求两个数组中重复的元素 lamdba

1、第一种普通的利用for循环:

public static void main(String[] args) {
		Integer[] arr1 = { 1, 2, 5, 2, 6, 8, 9 };
		Integer[] arr2 = { 2, 3, 4, 6, 9, 10 };

		Set sames = getSames(arr1, arr2);
		
		for (Integer i : sames) {
			System.out.println(i);
		}

	}

	public static Set getSames(Integer[] a, Integer[] b) {
		Set sames = new HashSet();
		Set set = new HashSet(Arrays.asList(a));

		for (Integer i : b) {
			if (!set.add(i))
				sames.add(i);
		}

		return sames;
	}

第二种:利用jdk1.8的lamdba语法糖

	public static void main(String[] args) {
		Integer[] arr1 = { 1, 2, 5, 2, 6, 8, 9 };
		Integer[] arr2 = { 2, 3, 4, 6, 9, 10 };

		
		Set sames = getSamesLambda(arr1, arr2);
		for (Integer i : sames) {
			System.out.println(i);
		}

	}


	public static Set getSamesLambda(Integer[] a, Integer[] b) {
		Set bb = new HashSet(Arrays.asList(b));

		List sames = Arrays.asList(a).stream().filter(i -> !bb.add(i)).collect(Collectors.toList());

		return new HashSet(sames);
	}

 

你可能感兴趣的:(基础知识)