fork download
  1. import java.util.List;
  2. import java.util.function.Predicate;
  3. import java.util.stream.Collectors;
  4.  
  5. public final class Main {
  6.  
  7. public static void main(String[] args) {
  8. Predicate<String> p = s -> s.startsWith("b");
  9. findFirst(p);
  10. limitList(p);
  11. }
  12.  
  13. public static void findFirst(Predicate<String> matchesFavorite) {
  14. var firstFavorite = List.of("foo", "bar", "baz")
  15. .stream()
  16. .filter(matchesFavorite)
  17. .findFirst();
  18. firstFavorite.ifPresent(s -> System.out.println("A:" + s));
  19.  
  20. // As a result, it is equivalent to the following code:
  21. List.of("foo", "bar", "baz")
  22. .stream()
  23. .filter(matchesFavorite)
  24. .findFirst()
  25. .ifPresent(s -> System.out.println("B:" + s));
  26. }
  27.  
  28. public static void limitList(Predicate<String> matchesFavorite) {
  29. var favoriteList = List.of("foo", "bar", "baz")
  30. .stream()
  31. .filter(matchesFavorite)
  32. .limit(1)
  33. .collect(Collectors.toList());
  34.  
  35. favoriteList.forEach(s -> System.out.println("C:" + s));
  36.  
  37. // Or
  38. for (var s : favoriteList) {
  39. // This loop only runs once at most.
  40. System.out.println("D:" + s);
  41. }
  42.  
  43. // Or again, it could be as follows, but...
  44. if (favoriteList.size() != 0) {
  45. var s = favoriteList.get(0);
  46. System.out.println("E:" + s);
  47. }
  48.  
  49. // As a result, it is equivalent to the following code:
  50. List.of("foo", "bar", "baz")
  51. .stream()
  52. .filter(matchesFavorite)
  53. .limit(1)
  54. .forEach(s -> System.out.println("F:" + s));
  55. }
  56. }
  57.  
Success #stdin #stdout 0.1s 36696KB
stdin
Standard input is empty
stdout
A:bar
B:bar
C:bar
D:bar
E:bar
F:bar