简体   繁体   English

从地图或数组列表中删除多个出现值

[英]Remove Multiple occurance values from map or arraylist

("A", "1");    ("B", "2");    ("C", "2");    ("D", "3");    ("E", "3");    

I have a map with duplicate values like above我有一张地图,上面有重复的值

I would like to the map to have我想要地图有

("A", "1");

And in case of list如果是列表

if list contains {1,2,2,3,3,4,5}如果列表包含{1,2,2,3,3,4,5}

i want {1,4,5}我想要{1,4,5}

Here is a Java 7 solution for the ArrayList case:这是 ArrayList 案例的 Java 7 解决方案:

Map<String, Integer> counts = new HashMap<>();
for (String elem : list) {
    Integer count = counts.get(elem);
    if (count == null) {
        counts.put(elem, 1);
    } else {
        counts.put(elem, count + 1);
    }
}

Iterator<String> it = list.iterator();
while (it.hasNext()) {
    int count = counts.get(it.next());
    if (count > 1) {
        it.remove();
    }
}

Note that this is not efficient.请注意,这效率不高。 In the worst-case it is O(N^2) , because it.remove() is an O(N) operation for an ArrayList .在最坏的情况下,它是O(N^2) ,因为it.remove()ArrayListO(N)操作。

However, it should be sufficient to understand the basic approach that needs to be taken.但是,了解需要采取的基本方法就足够了。 (Tagir's Java 8 solutions are doing roughly the same thing as this code ... except that they are building lists and taking list lengths instead of counting.) (Tagir 的 Java 8 解决方案与此代码大致相同……除了它们构建列表并获取列表长度而不是计数。)

Here's Java-8 solution for both tasks:这是针对这两个任务的 Java-8 解决方案:

public static <K, V> Map<K, V> noDups(Map<K, V> input) {
    Map<V, List<Entry<K, V>>> counts = input.entrySet().stream()
            .collect(groupingBy(Entry::getValue));
    return counts
            .values().stream().filter(list -> list.size() == 1)
            .collect(toMap(list -> list.get(0).getKey(), list -> list.get(0).getValue()));
}

public static <T> List<T> noDups(Collection<T> input) {
    LinkedHashMap<T, Long> counts = input.stream()
            .collect(groupingBy(Function.identity(), LinkedHashMap::new, counting()));
    return counts
            .entrySet().stream().filter(e -> e.getValue() == 1l)
            .map(Entry::getKey).collect(toList());
}

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

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