tuturyokgaming
tuturyokgaming

Reputation: 259

Java remove data that is duplicated

Is it possible to get all the distinct values in an arraylist or hashmap?

Let's say for example I have elements on arraylist like this :

123, 123, 456, 123, 456, 000

And in HashMap :

123, test1
123, test2
456, test3
123, test4
000, test5

Upvotes: 0

Views: 89

Answers (5)

MadConan
MadConan

Reputation: 3767

If you are using a Map, by definition the keys will be unique. For implementations of List there are a few options. For Java 5 through Java 7

public <T> List<T> removeDuplicates(List<T> list){
    Set<T> set = new LinkedHashSet<>(list);
    return new ArrayList<>(set);
}

With Java 8

public <T> List<T> removeDuplicatesJava8(List<T> list){
    return list.stream().distinct().collect(Collectors.toList());
}

Upvotes: 0

Binkan Salaryman
Binkan Salaryman

Reputation: 3048

You could use a Map<K, List<V>> (or Map<K, V[]>) if you like to map multiple values to a key:

Code:

public static void main(String[] args) {
    Map<Integer, List<String>> data = new HashMap<>();
    add(data, 123, "test1");
    add(data, 123, "test2");
    add(data, 456, "test3");
    add(data, 123, "test4");
    add(data,   0, "test5");
    data.forEach((k, v) -> System.out.println(k + " -> " + v));
}

static <K, V> void add(Map<K, List<V>> listMap, K key, V value) {
    List<V> values = listMap.get(key);
    if(values == null) {
        values = new ArrayList<V>();
        listMap.put(key, values);
    }
    values.add(value);
}

Output:

0 -> [test5]
456 -> [test3]
123 -> [test1, test2, test4]

Upvotes: 0

Anil Reddy Yarragonda
Anil Reddy Yarragonda

Reputation: 767

Keys should be unique in HashMap. if you are choosing duplicate keys then existing key value will be replace with new value.

if you want to avoid duplicate then use Set.

Upvotes: 4

Davide Lorenzo MARINO
Davide Lorenzo MARINO

Reputation: 26926

To get a Collection of unique elements from a List you can do that

Set<Object> set = new HashSet<Object>(nonUniqueList);

Upvotes: 0

Mathivanan
Mathivanan

Reputation: 369

HashMaps don't allow duplicate keys. If you enter a key which is already there then it replaces it with the new one.

Upvotes: 0

Related Questions