Java 8 Streams Map Examples

Convert one value to another in a Streams Operation

“Always and never are two words you should always remember never to use. ” ― Wendell Johnson

1. Introduction

Do you know about Java 8 Streams?

Java 8 streams is a very powerful facility for working with collections. What formerly required multiple lines of code and loops can now be accomplished with a single line of code. A part of Java 8 streams is the map() facility which can map one value to another in a stream. In this article, let us examine some common use cases where map() is useful.

2. The Function argument to the map() Method

The map() method is defined as follows:

<R> Stream<R> map(Function<? super T,? extends R> mapper);

This complicated looking definition is stating that the map() method accepts a Function which converts values of type T into values of type R. This is a well-known example which converts a String to an Integer. The function referred to is called a method reference.

Function<String,Integer> func = Integer::parseInt;

The types being converted need not be different. Consider this example of a Function which converts a name to a value. In contrast to the above, the function definition is an explicit lambda.

Function<String,String> f = name -> System.getenv(name);

Here is an example of a multi-line function which splits a String and returns the result with the first item skipped:

Pattern pattern = Pattern.compile(",");
Function<String,String[]> f = x -> {
    String[] arr = pattern.split(x);
    return Arrays.copyOfRange(arr, 1, arr.length);
};

3. Converting a List of Strings to Uppercase

Consider a list of strings which you need to convert to uppercase. Pre-java-8 you would have to have a loop for making this conversion.

List<String> lcarr = Arrays.asList("a", "b", "C", "d", "e");
List<String> ucarr = new ArrayList<>();
for (String s : lcarr) ucarr.add(s.toUpperCase());
for (String s : ucarr) System.out.println(s);

Using java 8 streams and map(), you can rewrite the above as:

List<String> ucarr = lcarr.stream().map(x -> x.toUpperCase()).collect(Collectors.toList());
ucarr.forEach(System.out::println);

The map() invocation can also be written as (using method references, also new in java 8):

List<String> ucarr = lcarr.stream().map(String::toUpperCase).collect(Collectors.toList());

4. Extract Specified Columns from a CSV File

The following example streams the lines from a file, splits each line using a regular expression and selects the first and third columns for printing.

Pattern pattern = Pattern.compile(",");
Files
    .lines(Paths.get(file))
    .skip(1)
    .map(str -> pattern.split(str))
    .forEach(arr -> System.out.println(arr[0] + " -> " + arr[2]));

And this one selects the fourth field from the CSV, converts the string to a Float and collects the results in a List.

Pattern pattern = Pattern.compile(",");
List<Float> scores = Files
    .lines(Paths.get(file))
    .skip(1)
    .map(str -> pattern.split(str)[3])
    .map(Float::parseFloat)
    .collect(Collectors.toList());

5. List Files in a Directory and Convert to URI

The following example lists out the entries in a directory.

Files.list(Paths.get(dir)).forEach(System.out::println);

To obtain the list of Path entries in a directory:

List<Path> entries = Files.list(Paths.get(dir)).collect(Collectors.toList());

Convert the entries to URIs:

List<URI> uris = Files.list(Paths.get(dir)).map(Path::toUri).collect(Collectors.toList());

Conclusion

In this article, we learned how to use the map() operation in java 8 streams. This operation is used to map from one value to another within the stream.