同一组数据分组 需求:一个 list 里可能会有出现一个用户多条数据的情况。要把多条用户数据合并成一条。
public static void main(String[] args) {
List<User> users = Arrays.asList(
new User(1, "liu big big", "123456789"),
new User(2, "liu big big", "987654321"),
new User(3, "su xiao xiao", "55555555")
);
Map<String, Set<User>> map = new HashMap<>();
for (User user : users) {
Set<User> userSet = map.get(user.getName());
if (null == userSet) {
userSet = new HashSet<>();
userSet.add(user);
map.put(user.getName(), userSet);
} else {
userSet.add(user);
}
}
Set<String> keySet= map.keySet();
Iterator<String> it = keySet.iterator();
while(it.hasNext()){
String key = it.next();
Set<User> user = map.get(key);
System.out.println(user.toString());
}
}
}
class User {
public User(Integer id, String name, String phone) {
this.id = id;
this.name = name;
this.phone = phone;
}
private Integer id;
private String name;
private String phone;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}