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
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.
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());
}
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]
123again as a key in aMap