相关疑难解决方法(0)

如何使用Java 8 Stream从某些类属性中获取List?

我有一个List<Person>.我需要List从一个属性获得Person.

例如,我有一个Person班级:

class Person
{
    private String name;
    private String birthDate;
    public String getName() {
        return name;
    }
    public String getBirthDate() {
        return birthDate; 
    }
    Person(String name) {
        this.name = name;
    }
}

List<Person> personList = new ArrayList<>();
personList.add(new Person("David"));
personList.add(new Person("Joe"));
personList.add(new Person("Michel"));
personList.add(new Person("Barak"));
Run Code Online (Sandbox Code Playgroud)

我想获得StreamAPI 的名称列表,如下所示:

List<String> names = personList.stream().somecode().collect(Collectors.toList());
names.stream().forEach(System.out::println);

#David
#Joe
#Michel
#Barak
Run Code Online (Sandbox Code Playgroud)

此代码不起作用:

public class Main 
{
    public static void main(String[] args) 
    {
        List<Person> personList …
Run Code Online (Sandbox Code Playgroud)

java collections java-8 java-stream

108
推荐指数
1
解决办法
12万
查看次数

使用java 8 api打印列表项

我可以使用类似的东西:

 .forEach(System.out::print)
Run Code Online (Sandbox Code Playgroud)

打印我的列表项,但如果我在打印前有其他操作要做,我不能使用它:

mylist.replaceAll(s -> s.toUpperCase()).forEach(System.out::print)
Run Code Online (Sandbox Code Playgroud)

我收到一个错误:无法取消引用void

java java-8

24
推荐指数
2
解决办法
4万
查看次数

标签 统计

java ×2

java-8 ×2

collections ×1

java-stream ×1