📜  Java中的流式 mapToDouble() 示例

📅  最后修改于: 2022-05-13 01:55:05.196000             🧑  作者: Mango

Java中的流式 mapToDouble() 示例

Stream mapToDouble(ToDoubleFunction 映射器)返回一个 DoubleStream,其中包含将给定函数应用于此流的元素的结果。

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

句法 :

DoubleStream mapToDouble(ToDoubleFunction mapper)

Where, A sequence of primitive double-valued
elements and T is the type of stream elements. 
mapper is a stateless function which is applied
to each element and the function returns the new stream.

示例 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 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 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