Today suddenly want to use Java implementation of how to use the set to achieve the intersection, the set and the difference set of the operation! The main point is to look at the Python language when it comes to mind.
Implements the set set that is used primarily, and the set set is characterized by the non-repetition of elements within the collection.
Specific code:
1 PackageCom.chengxuyuanzhilu;2 3 ImportJava.util.HashSet;4 ImportJava.util.Set;5 6 Public classcollectionoperation {7 Public Static voidMain (string[] args) {8set<integer> result =NewHashset<integer>();9Set<integer> Set1 =NewHashset<integer>() {Ten Private Static Final LongSerialversionuid = 1L; One { AAdd (1); -Add (3); -Add (5); the }}; - -Set<integer> Set2 =NewHashset<integer>(){ - Private Static Final LongSerialversionuid = 1L; + { -Add (1); +Add (2); AAdd (3); at }}; - - //intersection - result.clear (); - Result.addall (SET1); - Result.retainall (Set2); inSystem.out.println ("Intersection:" +result); - to //Difference Set + result.clear (); - Result.addall (SET1); the Result.removeall (Set2); *SYSTEM.OUT.PRINTLN ("Difference set:" +result); $ Panax Notoginseng //and set - result.clear (); the Result.addall (SET1); + Result.addall (Set2); ASystem.out.println ("and set:" +result); the + } -}
The results of the operation are as follows:
Java Collection operations: intersection, set, set difference