简体   繁体   English

Java删除重复的数据

[英]Java remove data that is duplicated

Is it possible to get all the distinct values in an arraylist or hashmap? 是否有可能在arraylist或hashmap中获得所有不同的值?

Let's say for example I have elements on arraylist like this : 假设例如我在arraylist上有这样的元素:

123, 123, 456, 123, 456, 000

And in HashMap : 在HashMap中:

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

Keys should be unique in HashMap. 键在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 . 如果要避免重复,请使用Set

HashMaps don't allow duplicate keys. HashMaps不允许重复的键。 If you enter a key which is already there then it replaces it with the new one. 如果输入的密钥已经存在,则将其替换为新密钥。

If you are using a Map , by definition the keys will be unique. 如果使用Map ,那么根据定义,键将是唯一的。 For implementations of List there are a few options. 对于List实现,有一些选项。 For Java 5 through Java 7 对于Java 5至Java 7

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

With Java 8 使用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: 如果要将多个值映射到键Map<K, List<V>>可以使用Map<K, List<V>> (或Map<K, V[]> ):

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]

为了得到一个Collection ,从一个独特的元素的List ,你可以这样做

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM