Java functional programming

From wikinotes


streams

Streams are the primary interface for dealing with functional programming paradigms in java.

Streams are covered in much greater detail in java datatypes, but here are the basics.

import java.util.stream.Stream;

Stream stream = Stream.of("alex", "courtney", "sam");  // create stream
list.stream();                                         // stream from list
Arrays.stream({"a", "b", "c"});                        // stream from array

stream.collect(Collectors.toList());                  // stream to list
stream.toArray(String[]::new);                        // stream to array
stream.iterate()

map

// make all names uppercase
String[] names = {"courtney", "alex", "sam"};
Stream<String> stream = Arrays.stream(names);
stream.map(s -> s.toUpperCase());

filter

Filter eliminates entries from a list if the result of a function is not true.

// return only names longer than 4 chars
String[] names = {"courtney", "alex", "sam"};
Stream<String> stream = Arrays.stream(names);
stream.filter(s -> s.length() > 4);

reduce

reduce operations stack the results of a function on top of it's result for each item in a list.

some examples:

  • sum of all integers in a list
  • multiply all integers in a list
Integer[] numbers = {1, 2, 3, 4};

Stream<Integer> stream = Arrays.stream(numbers);

// builtin reduce functions
stream.sum();
stream.average();

// reduce
stream.reduce(result, (arg,) -> result * arg)