Java Stream API to find a lenth of object (the length of toString())

63 Views Asked by At

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?

1

There are 1 best solutions below

0
Christopher Schneider On BEST ANSWER

You didn't include a complete example, but it looks like you have this object:

Collection<Person> people;

If you re-write what you're doing in a traditional for loop, this is what you're trying to do:

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

Obviously, a Person isn'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:

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

As a traditional loop:

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