streamtests
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package org.pierre.streams; | |
import org.junit.jupiter.api.Test; | |
import java.io.BufferedReader; | |
import java.io.FileReader; | |
import java.nio.file.Files; | |
import java.nio.file.Path; | |
import java.nio.file.Paths; | |
import java.util.ArrayList; | |
import java.util.Arrays; | |
import java.util.Iterator; | |
import java.util.List; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
import java.util.stream.Stream; | |
public class StreamTest { | |
/** | |
* https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps | |
*/ | |
@Test | |
public void obtainStream() { | |
// From a Collection via the stream() and parallelStream() methods; | |
List<String> myStrings = List.of("a", "b", "c"); | |
Stream<String> myStream1 = myStrings.stream(); | |
// From an array via Arrays.stream(Object[]); | |
String[] myStringsArray = myStrings.toArray(new String[0]); | |
Stream<String> myStream2 = Arrays.stream(myStringsArray); | |
// From static factory methods on the stream classes, such as Stream.of(Object[]), IntStream.range(int, int) | |
// or Stream.iterate(Object, UnaryOperator); | |
Stream<String> myStream3 = Stream.of("a", "b", "c"); | |
IntStream myStream4 = IntStream.of(1, 2, 3); | |
Stream<Integer> myStream5 = Stream.iterate(1, integer -> integer++); | |
// using Builder | |
IntStream myStream6 = IntStream.builder().add(1).add(2).add(3).build(); | |
// Read file content From BufferedReader | |
try (BufferedReader br = new BufferedReader(new FileReader("listofwords.txt"))) { | |
Stream myStream7 = br.lines(); | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
} | |
// Read file content from Files and Paths | |
Path path = Paths.get("listofwords.txt"); | |
try (Stream<String> lines = Files.lines(path)) { | |
} | |
catch (Exception e) { | |
e.printStackTrace(); | |
} | |
// you can directly manipulate a Stream with an iterator | |
Iterator<Integer> iterator = myStream6.iterator(); | |
// you can change the list BEFORE you consume the stream, and change is reflected in Stream | |
List<String> l = new ArrayList(Arrays.asList("one", "two")); | |
Stream<String> sl = l.stream(); | |
l.add("three"); | |
String s = sl.collect(Collectors.joining(" ")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment