Java Stream mapToDouble()示例

Java Stream mapToDouble()示例

Stream mapToDouble(ToDoubleFunction mapper) 返回一个DoubleStream,由给定的函数应用于该流的元素的结果组成。

流mapToDouble(ToDoubleFunction mapper)是一个 中间操作。 这些操作始终是懒惰的。中间操作是在一个Stream实例上调用的,在它们完成处理后,会给出一个Stream实例作为输出:

语法:

DoubleStream mapToDouble(ToDoubleFunction < ? super T > mapper)

其中,A序列的原始双值
元素,T是流元素的类型。
mapper是一个无状态函数,它被应用于
到每个元素,并且该函数返回新的流。

例1: mapToDouble()的操作是选择满足给定功能的元素。

// Java code for Stream mapToDouble
// (ToDoubleFunction mapper) to get a
// DoubleStream by applying the given function
// to the elements of this stream.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // Creating a list of Strings
        List<String> list = Arrays.asList("10", "6.548", "9.12",
                                                    "11", "15");
  
        // Using Stream mapToDouble(ToDoubleFunction mapper)
        // and displaying the corresponding DoubleStream
        list.stream().mapToDouble(num -> Double.parseDouble(num))
                    .filter(num -> (num * num) * 2 == 450)
                    .forEach(System.out::println);
    }
}

输出:

15.0

例2: mapToDouble()的操作是返回一个字符串长度的平方流。

// Java code for Stream mapToDouble
// (ToDoubleFunction mapper) to get a
// DoubleStream by applying the given function
// to the elements of this stream.
import java.util.*;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // Creating a list of Strings
        List<String> list = Arrays.asList("CSE", "JAVA", "gfg",
                                                    "C++", "C");
  
        // Using Stream mapToDouble(ToDoubleFunction mapper)
        // and displaying the corresponding DoubleStream
        // which contains square of length of each element in
        // given Stream
        list.stream().mapToDouble(str -> str.length() * str.length())
                     .forEach(System.out::println);
    }
}

输出:

9.0
16.0
9.0
9.0
1.0

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程