streams - Applying a function to every element

map(Function): Applies Function to every object in the input stream, passing on the result values as the output stream.

// streams/FunctionMap.java
// (c)2017 MindView LLC: see Copyright.txt
// We make no guarantees that this code is fit for any purpose.
// Visit http://OnJava8.com for more book information.

import java.util.*;
import java.util.function.*;
import java.util.stream.*;

class FunctionMap {
  static String[] elements = {"12", "", "23", "45"};

  static Stream<String> testStream() {
    return Arrays.stream(elements); // Returns a sequential Stream with the specified array as its source. since 1.8
  }

  static void test(String descr, Function<String, String> func) {
    System.out.println(" ---( " + descr + " )---");
    testStream().map(func).forEach(System.out::println); // map() Returns a stream consisting of the results of applying the given function to the elements of this stream.
  }

  public static void main(String[] args) {

    test("add brackets", s -> "[" + s + "]");

    test(
        "Increment",
        s -> { // please note this usage. 
          try {
            return Integer.parseInt(s) + 1 + "";
          } catch (NumberFormatException e) {
            System.out.println(123);
            return s;
          }
        });

    test("Replace", s -> s.replace("2", "9"));

    test("Take last digit", s -> s.length() > 0 ? s.charAt(s.length() - 1) + "" : s);
  }
}
/* My Output:
 ---( add brackets )---
[12]
[]
[23]
[45]
 ---( Increment )---
13
123

24
46
 ---( Replace )---
19

93
45
 ---( Take last digit )---
2

3
5
*/

references:

1. On Java 8 - Bruce Eckel

2. https://docs.oracle.com/javase/8/docs/api/java/util/Arrays.html#stream-T:A-

3. https://github.com/wangbingfeng/OnJava8-Examples/blob/master/streams/FunctionMap.java

4. http://hg.openjdk.java.net/jdk8/jdk8/jdk/file/687fd7c7986d/src/share/classes/java/util/Arrays.java

5. https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#map-java.util.function.Function-


版权声明:本文为wangbingfengf98原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。