I'm starting to get acquainted with Java and there are some features which I really like, e.g. using Predicate with .filter() and Function with .map(). This is a really nice functional approach. I have three questions about this code:
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
import java.util.function.Predicate;
public class ProcessList {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 4, 3, 2, 14, 1, -1, 0, 1, 5, 9, 0, 1);
Predicate<Integer> gt3 = (n) -> n > 3;
Function<Integer, Integer> plus11 = (n) -> n + 11;
List<Integer> numbersProcessed = numbers
.stream()
.filter(gt3)
.map(plus11)
.toList();
}
}
Regarding
Predicate: at the moment the number3is hard-coded. Say I want a dynamic predicate which is created at runtime, e.g.(n) -> n > x, withxbeing some Integer. How could I create a dynamic Predicate object? I tried something usingnew Predicate(), but this didn't seem right.Same as 1. regarding
Function: say I don't want plus11, but(n) -> n + x, withxbeing some Integer supplied at runtime. How can I create a dynamic Function object?The
.filter(),.map(), and.toList()operations make me think: Java is not a functional language by design. Since the essence of functional languages is to manipulate lists all the time, those languages are optimized to constantly produce new lists from existing lists, the more so as functional languages do not allow in-place manipulations on objects in principle. I was wondering: say there is a large list, containing millions of items. Will these kinds of list manipulations have a significant impact on Java's performance? In essence: what is the cost of using the functional approach in Java?
Thank you very much and have a nice day.