java - How to remove all duplicates from an array -


i want remove every duplicate array in java , store remaining integers in same array.

e.g.: int[] = { 5,5,5,3,4,4,2,2,1}; ==> int[] = {3,1};

so far have tried using:

set<integer> set = new hashset<integer>();  (int = 0; < array.length; i++) {   set.add(array[i]); } 

it appears though, removes 1 of duplicates , not both.

any appreciated.

you can use hashmap maintain count of each element , remove elements have count greater 1.

public int[] removeduplicates(int[] arr) {    map<integer, integer> countmap = new linkedhashmap<>(); // maintain order    (int n : arr) {       integer count = countmap.get(n);       if (count == null) {          count = 0;       }       count++;       countmap.put(n, count);    }     for(iterator<map.entry<string, string>> = countmap.entryset().iterator(); it.hasnext(); ) {       map.entry<string, string> entry = it.next();       if (entry.getvalue() > 1) {          it.remove();       }    }     return new arraylist<>(countmap.keyset()).toarray(new int[0]); } 

Comments

Popular posts from this blog

How to understand 2 main() functions after using uftrace to profile the C++ program? -

c# - Update a combobox from a presenter (MVP) -

How to put a lock and transaction on table using spring 4 or above using jdbcTemplate and annotations like @Transactional? -