Java lambda技巧-list按指定属性分组
在Java中,你可以使用Lambda表达式将List按照某个属性值进行分组。下面是一个示例代码,将List按照年龄进行分组:
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
public class ListGroupingExample {
public static void main(String[] args) {
List<Person> personList = Arrays.asList(
new Person("Alice", 25),
new Person("Bob", 30),
new Person("Charlie", 25),
new Person("Dave", 30)
);
Map<Integer, List<Person>> ageGroupMap = personList.stream()
.collect(Collectors.groupingBy(Person::getAge));
ageGroupMap.forEach((age, group) -> {
System.out.println("Age: " + age);
System.out.println("People: " + group);
System.out.println();
});
}
}
class Person {
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return name;
}
}
在上面的示例中,我们有一个包含Person对象的List。我们使用stream()
方法将List转换为流,然后使用Collectors.groupingBy()
方法按照Person对象的age属性进行分组。groupingBy()
方法接受一个参数,即分组的依据,这里我们使用Person::getAge
作为分组依据。
运行上述代码,将输出以下结果:
Age: 25
People: [Alice, Charlie]
Age: 30
People: [Bob, Dave]
这里我们按照年龄将Person对象分成了两个组。每个组的键是年龄,值是对应年龄的Person对象列表。
你可以根据自己的需求修改代码来按照不同的属性进行分组。