[英]How to find keys in the HashMap<String, LinkedList<String>> which have one or more similar values in LinkedList<String>
So I am trying to solve the following problem, I used HashMap as DS to Store the input. 因此,我试图解决以下问题,我使用HashMap作为DS来存储输入。
Question: Given an address book contains a list of contacts which were imported from different sources (outlook, linkedin, facebook) where each contact has 1 or more email addresses, write a function to group all contacts which share any email together 问题:给定一个通讯录,其中包含从不同来源(outlook,linkedin,facebook)导入的联系人列表,其中每个联系人具有一个或多个电子邮件地址,请编写一个函数以将共享任何电子邮件的所有联系人分组
Input: 输入:
C1: aaa@outlook.com, bbb@gmail.com
C2: ddd@outlook.com
C3: bbb@gmail.com, aaa@outlook.com, ccc@yahoo.com
C4: ccc@yahoo.com
C5: ddd@outlook.com
C6: eee@outlook.com
I am looking for output : 我正在寻找输出 :
((C1,C3,C4),(C2,C5),(C6))
I tried to get all values from hashmap into a hashset and then if the key in hashmap contains the value from set, I add the key to a result arraylist. 我试图将哈希表中的所有值都放入一个哈希集中,然后如果哈希表中的键包含集合中的值,则将该键添加到结果数组列表中。
The code I am using is : 我使用的代码是:
Set<String> set = new HashSet<>();
for(Map.Entry<String, LinkedList> entry: hm.entrySet()){
//System.out.println(entry.getKey()+" "+entry.getValue());
set.addAll(entry.getValue());
}
ArrayList<String> res1 = new ArrayList<>();
for(@SuppressWarnings("rawtypes") Map.Entry<String, LinkedList> entry: hm.entrySet()){
@SuppressWarnings("unchecked")
Iterator<String> curr = entry.getValue().iterator();
System.out.println(hm.entrySet());
while(curr.hasNext()){
System.out.println("Current= "+curr.next());
if(set.contains(curr.next())){
System.out.println(entry.getKey());
res1.add(entry.getKey());
}
}
}
System.out.println(set);
System.out.println(res1);
The output I am getting is : 我得到的输出是:
[C3=[aaa@gmail.com, bbb@outlook.com, ccc@yahoo.com], C4=[ccc@yahoo.com], C5=
[ddd@outlook.com], C6=[eee@outlook.com], C1=[bbb@outlook.com,
ddd@outlook.com], C2=[aaa@gmail.com]]
Current= aaa@gmail.com
C3
Current= ccc@yahoo.com
Exception in thread "main" java.util.NoSuchElementException
at java.util.LinkedList$ListItr.next(LinkedList.java:890)
at com.logicBuilding.MQ3_HashTable.getCommon(MQ3_HashTable.java:45)
at com.logicBuilding.MQ3_HashTable.main(MQ3_HashTable.java:7)
Replace this code of yours: 替换您的以下代码:
System.out.println("Current= "+curr.next());
if(set.contains(curr.next())){
with 同
String current = curr.next();
System.out.println("Current= " + current);
if(set.contains(current)) {
to avoid calling the next()
method without even checking if a next element is available. 避免在不检查next元素是否可用的情况
next()
调用next()
方法。 Also your your if
condition wants to check if the string you are currently looking at in is in your set
, not the next one already. 您的
if
条件也要检查您当前正在查看的字符串是否在您的set
,而不是下一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.