在Java中,foreach
循环和Lambda表达式可以很好地结合使用,以提高代码的简洁性和可读性。以下是一些使用foreach
循环和Lambda表达式的技巧:
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(name -> System.out.println(name));
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.forEach(System.out::println);
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> filteredNames = names.stream()
.filter(name -> name.length() > 4)
.collect(Collectors.toList());
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
List<String> upperCaseNames = names.stream()
.map(String::toUpperCase)
.collect(Collectors.toList());
List<String> names1 = Arrays.asList("Alice", "Bob");
List<String> names2 = Arrays.asList("Charlie", "David");
List<String> combinedNames = Stream.concat(names1.stream(), names2.stream())
.collect(Collectors.toList());
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.sort((name1, name2) -> name1.compareTo(name2));
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
names.parallelStream().forEach(name -> System.out.println(name));
reduce
操作计算集合中元素的总和:List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream().reduce(0, (a, b) -> a + b);
这些技巧可以帮助你更有效地使用foreach
循环和Lambda表达式来处理集合。请注意,这些示例仅适用于Java 8及更高版本。