How to remove duplicate elements from array in java?
As we use Api remove() in ArrayList and converting ArrayList to hashset so in the same way how we will remove duplicate elements in Array?
How to remove duplicate elements from array in java?
As we use Api remove() in ArrayList and converting ArrayList to hashset so in the same way how we will remove duplicate elements in Array?
Convert Array to Set
String someArray[] = {"a","b","c","b"};
Set<String> mySet = new HashSet<String>(Arrays.asList(someArray));
for (String string : mySet) {
System.out.println(string);
}
So that all the duplicate elements will be removed because Set don't support it.
Ouput : b c a
Ideally you should write these small codes yourself. But if you are inclined on using apis,
Convert the arrays into a list and then put that in a Set.
List<Card> cardsList = Arrays.asList(arr);
String[] array = new HashSet<>(Arrays.asList(new String[] { "a", "b", "c", "b", "a" })).toArray(new String[0]);
System.out.println(Arrays.toString(array));
OUTPUT:
[b, c, a]