在java中使用HashMap查找重复项不起作用



我是java新手。我在SO中搜索了这个问题,但我用自己的方式尝试了。我有地图,它正在打印以下内容:

Key = MX Week Email Pulls 010521 -010621_22780_1, Value = 010521010621
Key = MX Week Email Pulls 010721 -010921_23122, Value = 010721010921
Key = MX Week Email Pulls 010321 -010421_22779, Value = 010321010421
Key = MX Week Email Pulls 010521 -010621_22780, Value = 010521010621

由于,键是不同的,我想通过使用值来找到这些键的重复。由于上面的重复值是:

010521010621
010521010621

我试图通过增加计数值来找到重复:

public void doAnalysis(Map<String,String> mapAll) {
List<String> listOf=new ArrayList<>();
Map<String,Integer> putDupli=new HashMap<String, Integer>();
for (Map.Entry<String,String> entry : mapAll.entrySet()) {
System.out.println("Key = " + entry.getKey() +
", Value = " + entry.getValue());
if(!putDupli.containsValue(entry.getValue())) {
putDupli.put(entry.getValue(),0);
}
else {
putDupli.put(entry.getValue(),putDupli.get(entry.getKey())+1); 
}
}

System.out.println(putDupli);

}

线路System.out.println(putDupli);正在打印

{010521010621=0, 010721010921=0, 010321010421=0}

我的预期输出是:

{010521010621=2, 010721010921=0, 010321010421=0}

应为if(!putDupli.containsKey(entry.getValue())) {

而不是

if(!putDupli.containsValue(entry.getValue())) {

因为另一个映射将该值作为关键字。

此外,putDupli.put(entry.getValue(),putDupli.get(entry.getKey())+1);

应该是

putDupli.put(entry.getValue(), putDupli.get(entry.getValue()) + 1);

此外,您可能希望初始计数为1,而不是0。

如果一开始很难发现这些错误,请尝试使用调试器。

如果您使用的是java8,您可以使用Stream来获取计数

Map<String, Long> dupliMap = mapAll.values().stream()
.collect(Collectors.groupingBy(
x -> x,
Collectors.counting()
));

试试这个:

!putDupli.containsValue(entry.getValue().toString)

将Integer的值转换为String。

您可能需要考虑一种不同的方法。创建一个Map<Integer,List<Long>>来存储如下值:

String[] data = { "010521,010521010621",
"010721,010721010921", "010321,010321010421",
"010521,010521010621" };
Map<Integer, List<Long>> map =
Arrays.stream(data).map(str -> str.split(","))
.collect(Collectors.groupingBy(
arr -> Integer.valueOf(arr[0]),
Collectors.mapping(
arr -> Long.valueOf(arr[1]),
Collectors.toList())));

然后您可以找到每个值的计数。

for (List<Long> list : map.values()) {
System.out.println(list.get(0) + "=" + list.size());
}

打印

10321010421=1
10721010921=1
10521010621=2

相关内容

最新更新