2011-06-04 60 views
0

下午好的Java的Hashset搜索

在Java中,我有HashSet的含有可具有Properties对象User的名单:

  • 电子邮件
  • 计算机名

现在我的哈希集有以下值(上述对象列表)

email   | group | machinename 
---------------------------------------- 
[email protected] | hewitt | AP1 
[email protected] | test | AP1 
[email protected] | test | AP1 
[email protected]  | test | AP1 
[email protected] | project | AP1 
[email protected]  | project | AP1 

现在,我必须找到具有相同的电子邮件和机器,但不同的组名的记录在其上面的情况是:

[email protected] (which has "project" and "test" group) 
[email protected] (which has "hewitt" and "test" groups) 

我怎样才能找到使用Java代码?

+0

我现在总是做.. – Makky 2011-06-04 15:06:12

+0

这难道不是http://stackoverflow.com/questions/6212325/iterating-hashsets的副本? – 2011-06-04 15:15:37

+0

是!但无法在那里得到答案,所以不得不提出疑问 – Makky 2011-06-04 15:46:38

回答

3

这将不正是你想要什么:

Set<User> users = new HashSet<User>(); 
// ... 

Map<String, List<User>> hits = new HashMap<String, List<User>>(); 

for (User user : users) { 
    String key = user.getMachineName() + user.getEmail(); 
    List<User> list = hits.get(key); 
    if (list == null) { 
     list = new ArrayList<User>(); 
     hits.put(key, list); 
    } 
    list.add(user); 
} 

// Users are now grouped by their "machine name + email" as a single key 

for (Map.Entry<String, List<User>> hit : hits.entrySet()) { 
    if (hit.getValue().size() < 2) continue; 
    System.out.println("These users share the same email and machine name: " 
     + hit.getValue()); // hit.getValue() is an ArrayList<User> 
}