我有一些带有 ID 的对象。我希望根据 id 对对象进行分组。我的意思是,具有相同 id 的对象应该在一个组中。有什么想法吗?
例如:
id Name
1 Allah
1 Mohammad
2 Ali
2 Fatemeh
2 Hassan
3 hossein
3 Mahdi
3 Reza
最佳答案
假设您有这种类型:
class Person {
final int id;
final String name;
Person(int id, String name) {
this.id = id;
this.name = name;
}
}
然后您可以编写以下内容:
List<Person> people = Arrays.asList(new Person(1, "Allah"), new Person(1, "Mohammad"), ..);
Map<Object, List<Person>> peoplePerId =
people.stream()
.collect(Collectors.groupingBy(p -> p.id));
或者也许,甚至更好:
Map<Integer, List<String>> namesPerId =
people.stream()
.collect(Collectors.groupingBy(
p -> p.id,
Collectors.mapping(p -> p.name, Collectors.toList())
));
Java 8 之前的版本:
Map<Integer, List<String>> namesPerId = new HashMap<>();
for (Person person : people) {
List<String> list = namesPerId.get(person.id);
if (list == null) {
list = new ArrayList<>();
namesPerId.put(person.id, list);
}
list.add(person.name);
}
关于java - 如何根据id对某个对象进行分组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32022667/