标签:function puts 序列 示例 interface uppercase substring void 编程
Stream.map()是一个Stream的转换方法,把一个stream转换为另一个Stream,这2个Stream是按照映射函数一一对应的。
所谓map操作,就是把一种操作运算映射到序列的每个元素上。
例如:f(x)=x^2,对x计算它的平方,把这个函数映射到一个序列{1, 2, 3, 4, 5},就得到另一个序列{1, 4, 9, 16, 25}。这2个Stream是按照映射函数一一对应的
Stream<Integer> s = Stream.of(1, 2, 3, 4, 5);
Stream<Integer> s2 = s.map((n)->n*n);
map()接收的Function的接口,负责把1个T类型转换为R类型
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
@FunctionalInterface
public interface Function<T, R> {
R apply(T t);
}
public class StreamMapSample {
public static void main(String[] args){
String[] array = "Stream API supports functional-style operation".split(" ");
Stream<String> stream = Arrays.stream(array);
stream.map(String::toUpperCase).forEach(System.out::println);
}
}
import java.util.Arrays;
import java.util.stream.Stream;
class Person{
String name;
char gener;
public Person(String name,char gender){
this.name = name;
this.gener = gender;
}
public String toString(){
return "Person( "+name+", "+gener+" )";
}
}
public class StreamMapSample2 {
public static void main(String[] args){
String[] inputs = {"Bob,M","Alice,F","Time,M","Lily,F"};
Stream<String> names = Arrays.stream(inputs);
Stream<Person> persons = names.map((s)->{
int n = s.indexOf(",");
String name = s.substring(0,n);
char gender = s.charAt(n+1);
return new Person(name,gender);
});
persons.forEach(System.out::println);
}
}
map()方法:
标签:function puts 序列 示例 interface uppercase substring void 编程
原文地址:https://www.cnblogs.com/csj2018/p/11480006.html