import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "orange", "grape", "banana");
// forEach terminal operation
System.out.println("Printing each word:");
words.stream().forEach(System.out::println);
// count terminal operation
long wordCount = words.stream().count();
System.out.println("Total words count: " + wordCount);
// min/max terminal operation
Optional<String> minWord = words.stream().min(String::compareToIgnoreCase);
minWord.ifPresent(min -> System.out.println("Minimum word: " + min));
// findFirst terminal operation
Optional<String> firstWord = words.stream().findFirst();
firstWord.ifPresent(first -> System.out.println("First word: " + first));
// anyMatch terminal operation
boolean hasApple = words.stream().anyMatch(word -> word.equals("apple"));
System.out.println("Does the list contain 'apple'? " + hasApple);
// allMatch terminal operation
boolean allHaveLengthGreaterThanTwo = words.stream().allMatch(word -> word.length() > 2);
System.out.println("Do all words have length greater than 2? " + allHaveLengthGreaterThanTwo);
// noneMatch terminal operation
boolean noneHaveLengthGreaterThanTen = words.stream().noneMatch(word -> word.length() > 10);
System.out.println("Do none of the words have length greater than 10? " + noneHaveLengthGreaterThanTen);
// collect terminal operation toList
List<String> collectedList = words.stream().filter(word -> word.length() > 5).collect(Collectors.toList());
System.out.println("Words with length greater than 5: " + collectedList);
// reduce terminal operation
Optional<String> concatenatedWords = words.stream().reduce((word1, word2) -> word1 + ", " + word2);
concatenatedWords.ifPresent(concatenated -> System.out.println("Concatenated words: " + concatenated));
// toArray terminal operation
Object[] wordsArray = words.stream().toArray();
System.out.println("Words as array: " + Arrays.toString(wordsArray));
}
}
Printing each word:
apple
banana
orange
grape
banana
Total words count: 5
Minimum word: apple
First word: apple
Does the list contain 'apple'? true
Do all words have length greater than 2? true
Do none of the words have length greater than 10? true
Words with length greater than 5: [orange, banana]
Concatenated words: apple, banana, orange, grape, banana
Words as array: [apple, banana, orange, grape, banana]