import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
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;
}
}
public class Main {
public static void main(String[] args) {
List<Person> people = new ArrayList<>();
people.add(new Person("Alice", 30));
people.add(new Person("Bob", 25));
people.add(new Person("Charlie", 35));
// 获取所有人的名字
List<String> names = people.stream()
.map(Person::getName)
.collect(Collectors.toList());
// 打印所有人的名字
System.out.println(names); // 输出: [Alice, Bob, Charlie]
// 获取所有人年龄的列表
List<Integer> ages = people.stream()
.map(Person::getAge)
.collect(Collectors.toList());
// 打印所有人的年龄
System.out.println(ages); // 输出: [30, 25, 35]
}
}
Person
:包含两个字段 name
和 age
,并提供相应的 getter 方法。List<Person>
:用于存储多个 Person
对象。stream()
方法将 List<Person>
转换为流,然后使用 map()
方法提取每个对象的指定字段(如 name
或 age
),最后使用 collect(Collectors.toList())
将结果收集到一个新的列表中。这样可以方便地从 List
中提取某个字段的值。
上一篇:javaswing是什么意思
下一篇:linux卸载java
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站