Java extracts code samples for the same and different elements in two collections

  • 2020-11-25 07:15:02
  • OfStack

The sample code Shared in this article implements the extraction of the same and different elements from two collections

Here you need to use one of the methods provided by the Collection collection: removeAll(Cellection list), which is used to remove from the list all the elements contained in the specified collection.

Grammar removeAll (Collection < ? > c)

c: The collection object that contains the element removed from the list.

This method returns an boolean object, or true if the List collection object changes as a result of calling the removeAll method, or false if not. The implementation code is as follows:


import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class Test {
	public static void main(String args[]){
		// A collection of 1
		List _first=new ArrayList();
		_first.add("jim");
		_first.add("tom");
		_first.add("jack");
		// A collection of 2
		List _second=new ArrayList();
		_second.add("jack");
		_second.add("happy");
		_second.add("sun");
		_second.add("good");
		Collection exists=new ArrayList(_second);
		Collection notexists=new ArrayList(_second);
		exists.removeAll(_first);
		System.out.println("_second Not in _set The: "+exists);
		notexists.removeAll(exists);
		System.out.println("_second In the existed in _set The: "+notexists);
	}
}

Operation results:

Not found in _second: [happy, sun, good]
In _second in _set: [jack]

conclusion

That's all I have to say about the Java extract code samples for the same and different elements in two collections, and I hope you found them helpful. If there is any deficiency, please let me know. Thank you for your support!


Related articles: