-1

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?

assylias
  • 321,522
  • 82
  • 660
  • 783
Shekhar
  • 1
  • 1

3 Answers3

0

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 
Kick
  • 4,823
  • 3
  • 22
  • 29
0

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);
Hirak
  • 3,601
  • 1
  • 22
  • 33
0
    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]
Harmlezz
  • 7,972
  • 27
  • 35