如何从作为值添加的hashmap中删除重复列表

时间:2018-01-13 07:00:45

标签: java

下面是具有hashmap并添加列表作为键的程序。但是,正在添加重复列表。现在我想删除作为值驻留的所有重复列表。

import java.util.*;
public class Test {

public static void main(String args[]) {

    Map<String, List<Integer>> sample = new HashMap<String, List<Integer>>();
    List  first = new ArrayList();
    first.add(1);
    first.add(2);
    first.add(3);
    List second = new ArrayList();
    second.add(4);
    second.add(5);
    second.add(6);
    List  third = new ArrayList();
    third.add(1);
    third.add(2);
    third.add(3);
    sample.put("first", first);
    sample.put("second", second);
    sample.put("third", third);
    System.out.print(sample.size()); // Prints 3

    // Need to Remove the duplicate lists
    // Expects two keys with list first and second since third is duplicate value
    // 1,23 and 4,5,6 instead of 1,2,3 4,5,6 and 1,2,3
}
}

1 个答案:

答案 0 :(得分:0)

这段代码可能适合你 -

public static void main(String[] args) {
    Map<String, List<Integer>> sample = new HashMap<String, List<Integer>>();
    List first = new ArrayList();
    first.add(1);
    first.add(2);
    first.add(3);
    List second = new ArrayList();
    second.add(4);
    second.add(5);
    second.add(6);
    List third = new ArrayList();
    third.add(1);
    third.add(2);
    third.add(3);
    sample.put("first", first);
    sample.put("second", second);
    sample.put("third", third);
    removeDuplicates(sample);
    System.out.print(sample.size()); // now it will print 2

}

private static void removeDuplicates(Map<String, List<Integer>> sample) {
    Collection<List<Integer>> list = sample.values();
    for(Iterator<List<Integer>> itr = list.iterator(); itr.hasNext();) {
        if(Collections.frequency(list, itr.next())>1) {
            itr.remove();
        }
    }
}

此删除重复方法将从列表中删除重复值。