Monday, August 28, 2017

Java 8 Streams map()

In Java 8 Streams, map() is an intermediate function that can be used to apply a function to every element of a Stream. A few variations of map() include mapToInt(), mapToLong etc. which return streams of the corresponding types. The following examples show a few ways to use the map() function on streams. Append spaces to end of each word and print as a sentance.
  List<String> input = Arrays.asList("This", "is", "Java 8", "Stream", "map()", "Example");
  input.stream().map(x -> x.concat(" ")).forEach(System.out::print);
Convert Strings in a List to uppercase
  List<String> input = Arrays.asList("This", "is", "Java 8", "Stream", "map()", "Example");
  input.stream().map(String::toUpperCase).forEach(System.out::print);
Convert Stream of strings into stream of Integers which contain the lenght of the corresponding strings
  List<String> input = Arrays.asList("This", "is", "Java 8", "Stream", "map()", "Example");
  input.stream().mapToInt(String::length).forEach(System.out::println);
Applying Stream operations on java.util.Map involves creating a stream from the entrySet of the Map as shown below. The following piece of code prints out the values from the Map.
  Map<String, String> stockSymbols = new HashMap<String, String>();
  stockSymbols.put("GOOG", "Google");
  stockSymbols.put("AAPL", "Apple");
  stockSymbols.put("MSFT", "Microsoft");
  stockSymbols.put("BAC", "Bank Of America");
  stockSymbols.put("VZ", "Verizon");
  stockSymbols.put("AMZN", "Amazon");

  stockSymbols.entrySet().stream().map(Map.Entry::getValue).forEach(System.out::println);
Following is the full java class for the above examples.
package streams;

import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class StreamMapTest {

 public static void main(String[] args) {
  List<String> input = Arrays.asList("This", "is", "Java 8", "Stream", "map()", "Example");
  input.stream().map(x -> x.concat(" ")).forEach(System.out::print);

  input.stream().map(String::toUpperCase).forEach(System.out::print);

  input.stream().mapToInt(String::length).forEach(System.out::println);

  Map<String, String> stockSymbols = new HashMap<String, String>();
  stockSymbols.put("GOOG", "Google");
  stockSymbols.put("AAPL", "Apple");
  stockSymbols.put("MSFT", "Microsoft");
  stockSymbols.put("BAC", "Bank Of America");
  stockSymbols.put("VZ", "Verizon");
  stockSymbols.put("AMZN", "Amazon");

  stockSymbols.entrySet().stream().map(Map.Entry::getValue).forEach(System.out::println);
 }

}

No comments:

Post a Comment

Popular Posts