In the context of the introduction to “method references”, we read:
In the preceding code we used a method reference. Java lets us simply replace
the body of code with the method name of our choice. We will dig into this further...
One could add a note that this also works for java “Records”, but the getter is just the name of the member variable, here FooRecord::a
, rather than FooRecord::getA
public class SomeTest {
public static record FooRecord(String a) {
public String twiceString() {
return a + a;
}
}
@Test
public void joinFooRecord() {
List<FooRecord> foos = List.of(new FooRecord("a"),new FooRecord("b"),new FooRecord("c"));
String res_a = foos.stream().map(FooRecord::a).collect(Collectors.joining(","));
String res_toString = foos.stream().map(FooRecord::toString).collect(Collectors.joining(","));
String res_twiceString = foos.stream().map(FooRecord::twiceString).collect(Collectors.joining(","));
System.out.println(res_a);
System.out.println(res_toString);
}
}