Remove duplicates in Long array

I have two Long array elements and both have some values

Long[] firstArray = new Long[10];
Long[] secondArray = new Long[25];

Both the array may or may not be equal in size.

firstArray[0] = new Long("1"); 
firstArray[1] = new Long("2"); 
firstArray[2] = new Long("3"); 

secondArray [0] = new Long("2"); 
secondArray [1] = new Long("3"); 

I want to compare the secondArray with firstArray and create a new thirdArray with the values which are not in secondArray.

In the above example the thirdArray will have only 1

Answer

One possible solution would be to convert both of your arrays to List and use removeAll:

Long[] firstArray = new Long[10];
Long[] secondArray = new Long[25];

firstArray[0] = new Long("1"); 
firstArray[1] = new Long("2"); 
firstArray[2] = new Long("3"); 

secondArray [0] = new Long("2"); 
secondArray [1] = new Long("3"); 

List<Long> first = new ArrayList<>(Arrays.asList(firstArray));
List<Long> second = Arrays.asList(secondArray);

first.removeAll(second);

Long[] thirdArray = first.toArray(new Long[first.size()]);

Leave a Reply

Your email address will not be published. Required fields are marked *