Functional Programming with Java Tutorial
Selected Reading
- Discussion
- Resources
- Quick Guide
- Fixed Length Streams
- Infinite Streams
- Terminal methods
- Intermediate Methods
- Exception Handling
- Type Inference
- Pure Functions
- First Class Functions
- Returning a Function
- High Order Functions
- Collections
- Constructor References
- Method References
- Functional Interfaces
- Default Methods
- Lambda Expressions
- Reducing
- Currying
- Closure
- Optionals & Monads
- Parallelism
- Recursion
- Persistent Data Structure
- Eager vs Lazy Evaluation
- Functional Composition
- Functions
- Overview
- Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Collections
Functional Programming with Java - 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 pke filtering, mapping, reducing etc. on collections. See the example below −
import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; pubpc class FunctionTester { pubpc static void main(String[] args) { List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5); //Mapping //get pst of unique squares List<Integer> squaresList = numbers.stream().map( i -> i*i) .distinct().collect(Collectors.toList()); System.out.println(squaresList); //Filering //get pst 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); //Reducing int sum = numbers.stream().reduce((num1, num2) -> num1 + num2).orElse(-1); System.out.println(sum); } }
Output
[9, 4, 49, 25] [abc, bc, efg, abcd, jkl] 25Advertisements