下午好。
在Java中,我有HashSet,它包含对象User
的列表,它具有属性:
现在我的hashset有以下值(上面对象的列表)
email | group | machinename
----------------------------------------
robert@yahoo.com | hewitt | AP1
Mathew@gmail.com | test | AP1
melody@app.com | test | AP1
nick@ac.co | test | AP1
robert@yahoo.com | project | AP1
nick@ac.co | project | AP1
现在我必须找到那些具有相同电子邮件和机器但不同组名的记录,在上述情况下是:
nick@ac.co (which has "project" and "test" group)
robert@yahoo.com (which has "hewitt" and "test" groups)
如何使用java代码找到它?
答案 0 :(得分: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>
}