Java Stream API 查找对象长度(toString() 的长度)

问题描述 投票:0回答:1

我不明白为什么这个代码片段非静态方法不能从静态上下文中引用

people.stream()
                .mapToInt(String::length)
                .forEach(System.out::println);

这个**原因:不存在类型变量的实例,因此 Person 符合 String **

 people.stream()
                .map(String::length)
                .forEach(System.out::println);

相同的逻辑,但执行正确

people.stream()
           
                //.map(Main.Person::toString)
                //.mapToInt(String::length)
                .mapToInt(person->person.toString().length())
                .forEach(System.out::println);

为什么它如此不同并且 Stream 无法应用操作 String::length?

java-stream string-length
1个回答
0
投票

您没有包含完整的示例,但看起来您有这个对象:

Collection<Person> people;

如果您在传统的 for 循环中重写您正在做的事情,这就是您想要做的:

for(Person p : people) {
  String personString = (String)p;
  System.out.println(personString.length());
}

显然,

Person
不是字符串,所以编译会失败。

如果您想获得长度,您必须执行第三个示例中所做的操作。要将其写为流,您可以这样做:

people.stream()
  .map(Person::toString)
  .map(String::length)
  .forEach(System.out::println);

作为传统循环:

for(Person p : people) {
  String personString = p.toString();
  System.out.println(personString.length());
}
© www.soinside.com 2019 - 2024. All rights reserved.