OneCompiler

[Java] How to get difference between two arrays?

I want to find the difference between two arrays, how to do that in Java?

1 Answer

4 years ago by

We can stream on the Array and use filter to find the elements that are not exists in second array and finally convert the stream to array to create the diff. Following code shows how to do that

import java.util.Arrays;

public class JavaArrays {
	public static void main(String[] args) {
		String[] firstArray = { "a", "b", "c", "d"};
		String[] secondArray = { "b", "d" };
		
		String[] diff = Arrays.stream(firstArray)
			.filter(ele -> !Arrays.asList(secondArray)
								  .contains(ele))
			.toArray(String[]::new);
		
		
		System.out.println(Arrays.toString(diff));
	}
}

Output:

[a, c]

Try this code online here: https://onecompiler.com/java/3xmt7xcrd

4 years ago by Karthik Divi