This example demonstrates the use of functional programming in Java, using the functional features introduced in Java 8, such as streams and lambda expressions, to write clean and concise code that can be easily composed and reused.
Functional programming is a programming paradigm that emphasizes the use of pure functions and immutable data structures.
Here’s an example of functional program in Java:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.List; import java.util.stream.Collectors; public class FunctionalProgrammingExample { public static void main(String[] args) { List<Integer> numbers = List.of(1, 2, 3, 4, 5); List<Integer> squares = numbers.stream() .map(x -> x * x) .collect(Collectors.toList()); System.out.println(squares); } } |
The output of the above code would be:
In this example, we create a 'List'
of integers, representing a sequence of numbers. We then use the 'stream'
method to create a stream of these numbers and the 'map'
method to transform each number into its square. Finally, we use the 'collect'
method to collect the results into a 'List'
, which is then printed to the console.