I don't understand why this code snippet Non-static method cannot be referenced from a static context
people.stream()
.mapToInt(String::length)
.forEach(System.out::println);
This one **reason: no instance(s) of type variable(s) exist so that Person conforms to String **
people.stream()
.map(String::length)
.forEach(System.out::println);
The same logic but it's executed correctly
people.stream()
//.map(Main.Person::toString)
//.mapToInt(String::length)
.mapToInt(person->person.toString().length())
.forEach(System.out::println);
Why it's so different and Stream can't apply action String::length?
You didn't include a complete example, but it looks like you have this object:
If you re-write what you're doing in a traditional for loop, this is what you're trying to do:
Obviously, a
Personisn't a string, so compilation will fail.If you want to get the length, you'll have to do what you've done in your third example. To write it as a stream, you can do this:
As a traditional loop: