return | transfer |
---|---|
<R> Stream<R> |
map(Function<? super T,? extends R> mapper) |
The parameter is an Interface Function<T,R>
object, (the return type of Function
the apply(T t)
method that needs to manually implement the interface is R
)
? super T
is the type of the input, and
? extends R
the return type is clearR
1. The internal class implementation method, writing one: anonymous internal class The generic type
here Function
has <T,R>
become an <String,String>
overridden apply
method, the parameter type has T
become String
, and the return value type R
has also becomeString
public static void main(String[] args) throws IOException {
List<String> list1 = Arrays.asList("1","2","3");
list1.stream().map(
new Function<String, String>() {
@Override
public String apply(String s) {
s += s;
return s;
}
}
).forEach(System.out::println);
}
2. The internal class implementation method, the second way of writing: the internal class
public static void main(String[] args) throws IOException {
List<String> list1 = Arrays.asList("1","2","3");
list1.stream().map(
new Fun()
).forEach(System.out::println);
}
//实现接口时,泛型是写在接口上
static class Fun implements Function<String,String>{
//为什么要加static
@Override
public String apply(String s) {
s += s;
return s;
}
}
3.
lambda
The essence of using lambda is the Function
inner class
public static void main(String[] args) throws IOException {
List<String> list1 = Arrays.asList("1","2","3");
list1.stream().map(
x -> x+=x
).forEach(System.out::println);
}