| 6 | Includes examples with lists of numbers and words |
| 7 | */ |
| 8 | public class JavaStreams { |
| 9 | |
| 10 | private static final List<Integer> numbers = |
| 11 | List.of(10, 2, 21, 23, 22, 14, 16, 18, 19, 9, 4, 6, 7); |
| 12 | |
| 13 | private static final List<String> words = |
| 14 | List.of("apple", "bread", "tree", "computer", "name", "brain", "arm"); |
| 15 | |
| 16 | //Use stream to find all numbers that are greater than 10 |
| 17 | public static List<Integer> findAllNumbersGreaterThanTen(List<Integer> numbers){ |
| 18 | return numbers.stream() |
| 19 | .filter(number -> number > 10) |
| 20 | .sorted() |
| 21 | .collect(Collectors.toList()); |
| 22 | } |
| 23 | |
| 24 | //Use stream to find all numbers that contain the letter a |
| 25 | public static List<String> findAllWordsThatContainLetterA(List<String> words){ |
| 26 | return words.stream() |
| 27 | .filter(word -> word.contains("a")) |
| 28 | .collect(Collectors.toList()); |
| 29 | } |
| 30 | |
| 31 | //print out the origin lists, and then the changed lists |
| 32 | public static void main(String[] args) { |
| 33 | System.out.println("The unsorted array is: " |
| 34 | + numbers); |
| 35 | |
| 36 | System.out.println("The sorted array is: " |
| 37 | + numbers.stream().sorted().toList()); |
| 38 | |
| 39 | System.out.println("All numbers in the list greater than 10: " |
| 40 | + findAllNumbersGreaterThanTen(numbers)); |
| 41 | |
| 42 | System.out.println(); |
| 43 | |
| 44 | System.out.println("A list of words: " + words); |
| 45 | System.out.println("All words in the list that contain the letter A: " |
| 46 | + findAllWordsThatContainLetterA(words)); |
| 47 | } |
| 48 | } |
nothing calls this directly
no outgoing calls
no test coverage detected