Reputation: 333
I am trying to get the Java 8 stream equivalent of this old school code.
Set<String> studentNames = new HashSet<String>();
for(Student student : students){
String name =(student.getName());
studentNames.add(transform(name));
}
Student is inner static class while I need to call the api from non static method. transform is a static method. I tried something like this but it doesnt compile.. I get compiler error as static reference cannot be made from non static method...
studentNames = Stream.of(students)
.filter(Objects::nonNull)
.map(Student::getName)
.map(Transformer::transform)
.collect(Collectors.toSet());
Upvotes: 1
Views: 1751
Reputation: 4553
As Holger said in his comment, your problem is caused by calling Stream.of(students)
. If you look at of
's signature, you'll see that it expects either a single element or an array of elements. Hence, if you give it a collection, you'll get a stream of collections, not of the collection's elements:
Stream<String> s1 = Stream.of("hello");
Stream<String> s2 = Stream.of("hello", "world");
Stream<String> s3 = Stream.of(new String[] {"hello", "world"});
Stream<List<String>> s4 = Stream.of(Arrays.asList("hello", "world"));
Stream<String> s5 = Arrays.asList("hello", "world").stream();
Upvotes: 1
Reputation: 121028
Seems like your problem is here Transformer::transform
, you need an actual instance of transformer
to make this work.
Transformer t = new Transformer(...);
list.stream()
.filter(Objects::nonNull)
.map(Student::getName)
.map(t::transform)
.collect(Collectors.toSet());
Also it looks like Transformer
is just a Function<String, String>
btw.
Upvotes: 1