0

How to remove duplicate elements in an array??in java

{1,2,7,5,1,2,5,7} and explain me plz

27th Aug 2017, 2:26 AM
corejava
5 ответов
+ 3
Use a set instead or convert the array into a set: import java.util.Arrays; import java.util.HashSet; import java.util.Set; import java.util.stream.Collectors; public class Program { public static void main(String[] args) { // If using the class wrapper Integer for array // Integer[] x = {1,2,7,5,1,2,5,7}; // Set<Integer> y = new HashSet<Integer>(Arrays.asList(x)); // If using an int array int[] x = {1,2,7,5,1,2,5,7}; Set<Integer> y = new HashSet<Integer>(Arrays.stream(x).boxed().collect(Collectors.toList())); for(Integer i: y) { System.out.print(i + " "); } } }
27th Aug 2017, 2:48 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
You can also create a set of Integers like: Set<Integer> set = new HashSet<>(Arrays.asList(1,2,7,5,1,2,5,7)); OR: // Create an empty set Set<Integer> set = new HashSet<>(); set.add(1); set.add(2); set.add(7); set.add(5); set.add(1); // duplicate not added set.add(2); // duplicate not added set.add(5); // duplicate not added set.add(7); // duplicate not added
27th Aug 2017, 3:36 AM
ChaoticDawg
ChaoticDawg - avatar
+ 2
A set is a generic Collection Interface that will not contain duplicate elements. If an element that exists in the set is added to the set again that new element is discarded. When you create a set from a List it will go through each element of the List and add each non existing element to the set ignoring any duplicate elements. Since Set is a generic it will only accept something that derives from Object, so primitive types such as int, float, byte, double, boolean, etc are not allowed and instead require boxing in their class wrappers. Integer in the case of int. This: Integer[] x = {1,2,7,5,1,2,5,7}; Is equivalent to: int[] x = {1,2,7,5,1,2,5,7}; but each int is boxed in the Integer wrapper. Look into boxing, unboxing, and auto-boxing for more information. Here we create a List of type Integer from the Integer array (not int array) Arrays.asList(x) In this version, we create a List of type Integer from the int array (not Integer array) by first boxing each int into an Integer object. Arrays.stream(x).boxed().collect(Collectors.toList()) // Java 8 We then create a HashSet from the new Integer List Set<Integer> y = new HashSet<Integer>(); Look more into polymorphism, generics, and java collections. y is an unordered set containing only 1 of each Integer. Then we loop over each element within the HashSet y using a for each type loop: for(Integer i: y) { System.out.print(i + " "); } outputting each Integer in the Set.
27th Aug 2017, 3:37 AM
ChaoticDawg
ChaoticDawg - avatar
0
explain me this program plz
27th Aug 2017, 2:52 AM
corejava
0
I didn't understand this
27th Aug 2017, 2:53 AM
corejava