I am trying to achieve lazy evaluation using Supplier in a stream like this
public static void main(String[] args) {
Supplier<List<String>> expensiveListSupplier= getExpensiveList();
getList().stream()
.filter(s -> expensiveListSupplier.get().contains(s))
.forEach(System.out::println);
}
private static Supplier<List<String>> getExpensiveList() {
return () -> Stream
.of("1", "2", "3")
.peek(System.out::println)
.collect(Collectors.toList());
}
private static List<String> getList() {
return Stream.of("2", "3")
.collect(Collectors.toList());
}
But this will call getExpensiveList() method for every element in the list. I am trying not to be verbose and don't want to write something like this ie to add not empty checks and stuff.
public static void main(String[] args) {
Supplier<List<String>> expensiveListSupplier = getExpensiveList();
List<String> list = getList();
if (!list.isEmpty()) {
List<String> expensiveList = expensiveListSupplier.get();
list.stream()
.filter(expensiveList::contains)
.forEach(System.out::println);
}
}
private static Supplier<List<String>> getExpensiveList() {
return () -> Stream
.of("1", "2", "3")
.peek(System.out::println)
.collect(Collectors.toList());
}
private static List<String> getList() {
return Stream.of("2", "3")
.collect(Collectors.toList());
}