![](/img/trans.png)
[英]Adding to a linkedList in a HashMap<String, LinkedList>
[英]How to find keys in the HashMap<String, LinkedList<String>> which have one or more similar values in LinkedList<String>
因此,我试图解决以下问题,我使用HashMap作为DS来存储输入。
问题:给定一个通讯录,其中包含从不同来源(outlook,linkedin,facebook)导入的联系人列表,其中每个联系人具有一个或多个电子邮件地址,请编写一个函数以将共享任何电子邮件的所有联系人分组
输入:
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
我正在寻找输出 :
((C1,C3,C4),(C2,C5),(C6))
我试图将哈希表中的所有值都放入一个哈希集中,然后如果哈希表中的键包含集合中的值,则将该键添加到结果数组列表中。
我使用的代码是:
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);
我得到的输出是:
[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)
替换您的以下代码:
System.out.println("Current= "+curr.next());
if(set.contains(curr.next())){
同
String current = curr.next();
System.out.println("Current= " + current);
if(set.contains(current)) {
避免在不检查next元素是否可用的情况next()
调用next()
方法。 您的if
条件也要检查您当前正在查看的字符串是否在您的set
,而不是下一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.