0

Remove duplicates from sorted array

17th Sep 2017, 8:03 PM
Virendra Kumar
Virendra Kumar - avatar
2 Réponses
+ 4
You can also convert the set back to an array and use the array if you'd prefer. Type[] identifier = set.toArray(new Type[set.size()]); This will give you a new array that doesn't contain any duplicates from the first array. A full example with object types: import java.util.Set; import java.util.HashSet; import java.util.Arrays; public class Program { public static void main(String[] args) { // Array is an Integer object not int Integer[] myIntArr = { 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9 }; Set<Integer> myIntSet = new HashSet<Integer>(Arrays.asList(myIntArr)); Integer[] wrappedIntArr = myIntSet.toArray(new Integer[myIntSet.size()]); for(Integer i: wrappedIntArr) { System.out.println(i); } } } With primitive types: import java.util.Set; import java.util.HashSet; import java.util.Arrays; import java.util.stream.Collectors; public class Program { public static void main(String[] args) { int[] myIntArr = { 1, 1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9 }; Set<Integer> myIntSet = new HashSet<Integer>(Arrays.stream(myIntArr).boxed().collect(Collectors.toList())); Integer[] wrappedIntArr = myIntSet.toArray(new Integer[myIntSet.size()]);/ for(Integer i: wrappedIntArr) { System.out.println(i); } } } If you need more help, post your code, or be more specific with what you need.
17th Sep 2017, 9:08 PM
ChaoticDawg
ChaoticDawg - avatar
+ 2
You can convert it to a Set and use the set instead. Set<T> set = new HashSet<T>(Arrays.asList(array)); https://docs.oracle.com/javase/8/docs/api/java/util/Set.html https://docs.oracle.com/javase/8/docs/api/java/util/HashSet.html
17th Sep 2017, 8:10 PM
ChaoticDawg
ChaoticDawg - avatar