Aspects

Java 8 Onwards

Functional Programming

Streams

Useful Resources

Functional Programming - Collections



With Java 8 onwards, streams are introduced in Java and methods are added to collections to get a stream. Once a stream object is retrieved from a collection, we can apply various functional programming aspects like filtering, mapping, reducing etc. on collections.

Example - Usage of Mapping on Collections

FunctionTester.java

package com.tutorialspoint;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FunctionTester {    
   public static void main(String[] args) {               
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

      //Mapping
      //get list of unique squares
      List<Integer> squaresList = numbers.stream().map( i -> i*i)
         .distinct().collect(Collectors.toList());
      System.out.println(squaresList);
   } 
}

Output

Run the FunctionTester and verify the output.

[9, 4, 49, 25]

Example - Usage of Filtering on Collections

FunctionTester.java

package com.tutorialspoint;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class FunctionTester {    
   public static void main(String[] args) { 
      //Filering 
      //get list of non-empty strings
      List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
      List<String> nonEmptyStrings = strings.stream()
         .filter(string -> !string.isEmpty()).collect(Collectors.toList());
      System.out.println(nonEmptyStrings);
   } 
}

Output

Run the FunctionTester and verify the output.

[abc, bc, efg, abcd, jkl]

Example - Usage of Reducing on Collections

FunctionTester.java

package com.tutorialspoint;

import java.util.Arrays;
import java.util.List;

public class FunctionTester {    
   public static void main(String[] args) {               
      List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);

      //Reducing
      int sum = numbers.stream().reduce((num1, num2) -> num1 + num2).orElse(-1);
      System.out.println(sum);
   } 
}

Output

Run the FunctionTester and verify the output.

25
Advertisements