【发布时间】:2017-08-21 23:36:12
【问题描述】:
所以我正在尝试解决以下问题,我使用 HashMap 作为 DS 来存储输入。
问题: 给定地址簿包含从不同来源(outlook、linkedin、facebook)导入的联系人列表,其中每个联系人都有 1 个或多个电子邮件地址,编写一个函数将共享任何电子邮件的所有联系人分组
输入:
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))
我尝试将 hashmap 中的所有值放入一个 hashset,然后如果 hashmap 中的键包含 set 中的值,我将键添加到结果数组列表中。
我使用的代码是:
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())){next()方法的第二次调用在没有检查其他项目是否可用的情况下完成... -
你的输出对我来说不太有意义。为什么 C1 和 C4 在一个组中? C6 是否允许单独在一个组中,即使它有 0 个相似的值?
-
@4castle C1 和 C3 的共同点是 aaa@yahoo.com,C3 和 C4 的共同点是 ccc@yahoo.com,因此他们属于同一个人!
标签: java collections linked-list hashmap duplicates