在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及更高版本。