воскресенье, 12 мая 2024 г.

Stream in Java

    Java Streams is a powerful feature introduced in Java 8 that simplifies the processing of collections and sequences of data. Streams enable you to perform complex operations on data with concise and expressive code.

Stream is a sequence of data that you can process in a declarative and functional style. It allows you to perform operations such as filtering, mapping, and reducing on a collection of data. Streams can be used with various data sources, including arrays, collections, and even I/O channels.

Arrays: You can create a stream from an array using the Arrays.stream() method.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> nameStream = names.stream();

- Collections: Java collections such as lists, sets, and maps can be converted to streams using the stream() method.
List<String> names = Arrays.asList("Alice", "Bob", "Charlie");
Stream<String> nameStream = names.stream();

- I/O Channels: Java provides classes like BufferedReader for reading from input sources like files. These classes can be wrapped into streams using methods like lines().
try (Stream<String> lines = Files.lines(Paths.get("file.txt"))) {
// Process the lines in the file
} catch (IOException e) {
e.printStackTrace();
}

- Stream.of() is a static factory method in Java's Stream class that allows you to create a stream from a sequence of elements.
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);

Once you have a Stream, you can perform various operations on it. Stream operations can be categorized into two types: intermediate and terminal operations.

Intermediate operations transform the elements of the stream and produce a new stream as a result. Some common intermediate operations in Java streams include filter, map, flatMap, distinct, sorted, limit, and skip, among others.

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Main {
public static void main(String[] args) {
List<String> words = Arrays.asList("apple", "banana", "orange", "grape", "banana");

// Filter words starting with 'a'
List<String> filteredWords = words.stream()
.filter(word -> word.startsWith("a"))
.collect(Collectors.toList());
System.out.println("Words starting with 'a': " + filteredWords);

// Map each word to its length
List<Integer> wordLengths = words.stream()
.map(String::length)
.collect(Collectors.toList());
System.out.println("Word lengths: " + wordLengths);

// Remove duplicates
List<String> distinctWords = words.stream()
.distinct()
.collect(Collectors.toList());
System.out.println("Distinct words: " + distinctWords);

// Sort words alphabetically
List<String> sortedWords = words.stream()
.sorted()
.collect(Collectors.toList());
System.out.println("Sorted words: " + sortedWords);

// Limit to first 3 words
List<String> firstThreeWords = words.stream()
.limit(3)
.collect(Collectors.toList());
System.out.println("First three words: " + firstThreeWords);

// Skip first 2 words
List<String> skippedFirstTwoWords = words.stream()
.skip(2)
.collect(Collectors.toList());
System.out.println("Skipped first two words: " + skippedFirstTwoWords);
}
}

Words starting with 'a': [apple]
Word lengths: [5, 6, 6, 5, 6]
Distinct words: [apple, banana, orange, grape]
Sorted words: [apple, banana, banana, grape, orange]
First three words: [apple, banana, orange]
Skipped first two words: [orange, grape, banana]


Terminal operations in Java streams are the final operations that produce a result or a side-effect. Once a terminal operation is applied to a stream, it consumes the stream and produces a result, such as a list, a value, or even performing an action like printing elements.

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]

Комментариев нет:

Отправить комментарий