Java 8 Stream.map()
将 Stream<X>
转换为 Stream<Y>
。对于每个 X
类型的对象,都会创建一个新的 Y
类型的对象,并将其放入新的 Stream
中。
Stream map()
方法具有以下语法。
<R> Stream<R> map(Function<? super T,? extends R> mapper)
R
表示新流的元素类型。mapper
是一个无干扰、无状态的函数,适用于每个产生新值流的元素。R
的新对象流。Stream
接口有另外三个类似的方法,分别生成 IntStream
、LongStream
和 DoubleStream
分别经过map操作。
如果在 map()
操作之后创建的流被赋予返回类型,那么请考虑直接使用这些函数。
IntStream mapToInt(ToIntFunction<? super T> mapper)
LongStream mapToLong(ToLongFunction<? super T> mapper)
DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper)
map()
是一个中间操作。它返回一个新的 Stream
作为返回值。map()
操作接受一个 Function
,为输入流中的每个值调用它并产生一个发送到输出流的结果值。map()
方法用于将 X
的 Stream 转换为 Y
的 Stream。map()
操作不会像 flatMap()
操作那样展平流。在此示例中,我们将把 Stream<String>
转换为 Stream<Integer>
。这里的 mapper 函数 Integer::valueOf()
一次从 Stream 中取出一个字符串,并将 String
转换为 $ $$
。
然后它将 Integer
放入另一个流中,然后使用 Collectors.toList()
收集该流。
List<String> listOfStrings = Arrays.asList("1", "2", "3", "4", "5");
List<Integer> listOfIntegers = listOfStrings.stream()
.map(Integer::valueOf)
.collect(Collectors.toList());
System.out.println(listOfIntegers);
程序输出。
[1, 2, 3, 4, 5]
为 List
员工查找所有可能的 distinct 薪水的 Java 示例。
List<Employee> employeesList = Arrays.asList(
new Employee(1, "Alex", 100),
new Employee(2, "Brian", 100),
new Employee(3, "Charles", 200),
new Employee(4, "David", 200),
new Employee(5, "Edward", 300),
new Employee(6, "Frank", 300)
);
List<Double> distinctSalaries = employeesList.stream()
.map( e -> e.getSalary() )
.distinct()
.collect(Collectors.toList());
System.out.println(distinctSalaries);
程序输出。
[100.0, 200.0, 300.0]
请将您与 Java Stream API 中的Stream map() 方法 相关的问题发给我。
快乐学习!!
地址:https://www.cundage.com/article/stream-map-example.html