java-stream

How to create a two dimensional array from a stream in Java 8?

和自甴很熟 提交于 2019-12-01 03:28:15
I have a text file like this: ids.txt 1000 999 745 123 ... I want to read this file and load it in a two dimensional array. I expect to have an array similar to the one below: Object[][] data = new Object[][] { // { new Integer(1000) }, // { new Integer(999) }, // { new Integer(745) }, // { new Integer(123) }, // ... }; Here is the code I wrote: File idsFile = ... ; try (Stream<String> idsStream = Files.lines(idsFile.toPath(), StandardCharsets.US_ASCII)) { Object[][] ids = idsStream .filter(s -> s.trim().length() > 0) .toArray(size -> new Object[size][]); // Process ids array here... } When

How can I convert a Stream of Strings to Stream of String pairs?

半城伤御伤魂 提交于 2019-12-01 02:52:49
问题 I want to take a stream of strings and turn it into a stream of word pairs. eg: I have: { "A", "Apple", "B", "Banana", "C", "Carrot" } I want: { ("A", "Apple"), ("Apple", "B"), ("B", "Banana"), ("Banana", "C") } . This is nearly the same as Zipping, as outlined at Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip) However, that produces: { (A, Apple), (B, Banana), (C, Carrot) } The following code works, but is clearly the wrong way to do it (not thread safe etc etc): static

Do terminal operations on streams close the source? [duplicate]

给你一囗甜甜゛ 提交于 2019-12-01 02:50:48
This question already has an answer here: Do terminal operations close the stream? 2 answers Consider the following code: Path directory = Paths.get(/* some directory */); Files.list(directory).forEach(System.out::println); Does a terminal operation (like forEach ) close the underlying file that has been opened? Refer to the relevant parts of the javadoc of Files.list : The returned stream encapsulates a DirectoryStream. If timely disposal of file system resources is required, the try-with-resources construct should be used to ensure that the stream's close method is invoked after the stream

How do I iterate over a stream in Java using for? [duplicate]

拥有回忆 提交于 2019-12-01 02:39:50
This question already has an answer here: Why does Stream<T> not implement Iterable<T>? 9 answers I have this code: List<String> strings = Arrays.asList("a", "b", "cc"); for (String s : strings) { if (s.length() == 2) System.out.println(s); } I want to write it using a filter and a lambda: for (String s : strings.stream().filter(s->s.length() == 2)) { System.out.println(s); } I get Can only iterate over an array or an instance of java.lang.Iterable . I try: for (String s : strings.stream().filter(s->s.length() == 2).iterator()) { System.out.println(s); } And I get the same error. Is this even

stream and parallelStream

时光总嘲笑我的痴心妄想 提交于 2019-12-01 02:33:11
问题 I have a test code like this : List<Integer> list = new ArrayList<>(1000000); for(int i=0;i<1000000;i++){ list.add(i); } List<String> values = new ArrayList<>(1000000); list.stream().forEach( i->values.add(new Date().toString()) ); System.out.println(values.size()); Running this, I got a correct output: 1000000. However, if I change the stream() to parallelStream() , as this: list.parallelStream().forEach( i->values.add(new Date().toString()) ); I got a random output, e.g.: 920821. What's

Why doesn't Stream.limit work as expected in this snippet?

帅比萌擦擦* 提交于 2019-12-01 02:04:18
List<Integer> integer = Stream.generate(new Supplier<Integer>() { int i = 0 ; @Override public Integer get() { return ++i; } }).filter(j -> j < 5) .limit(10) // Note the call to limit here .collect(Collectors.toList()); Counter to my expectation, the collect call never returns. Setting limit before filter produces the expected result. Why? Since there are only 4 elements that pass the filter, limit(10) never reaches 10 elements, so the Stream pipeline keeps generating new elements and feeding them to the filter, trying to reach 10 elements that pass the filter, but since only the first 4

Comparison between legacy for loop, streams and parallelStream in Java 8

你。 提交于 2019-12-01 02:01:40
import java.util.ArrayList; import java.util.List; public class IterationBenchmark { public static void main(String args[]){ List<String> persons = new ArrayList<String>(); persons.add("AAA"); persons.add("BBB"); persons.add("CCC"); persons.add("DDD"); long timeMillis = System.currentTimeMillis(); for(String person : persons) System.out.println(person); System.out.println("Time taken for legacy for loop : "+ (System.currentTimeMillis() - timeMillis)); timeMillis = System.currentTimeMillis(); persons.stream().forEach(System.out::println); System.out.println("Time taken for sequence stream : "+

Why filter with side effects performs better than a Spliterator based implementation?

余生颓废 提交于 2019-12-01 01:47:03
问题 Regarding the question How to skip even lines of a Stream obtained from the Files.lines I followed the accepted answer approach implementing my own filterEven() method based on Spliterator<T> interface, e.g.: public static <T> Stream<T> filterEven(Stream<T> src) { Spliterator<T> iter = src.spliterator(); AbstractSpliterator<T> res = new AbstractSpliterator<T>(Long.MAX_VALUE, Spliterator.ORDERED) { @Override public boolean tryAdvance(Consumer<? super T> action) { iter.tryAdvance(item -> {}); /

Java 8 stream's toArray and size parameter

霸气de小男生 提交于 2019-12-01 01:39:29
I was wondering how stream().toArray[x -> new Integer[x]] knows what size of array to from? I wrote a snippet in which i created a list of an integer of size 4 and filtered the values and it created an array of length of the filtered stream, I could not see any method on stream to get a size of the stream. List<Integer> intList = new ArrayList<Integer>(); intList.add(1); intList.add(2); intList.add(3); intList.add(4); Integer[] array = intList.stream() .filter(x -> x > 2) .toArray(x -> { System.out.println("x --> " + x); return new Integer[x]; }); System.out.println("array length: " + array

What is the default Set/List implementation with Collectors in Java 8 Stream API?

狂风中的少年 提交于 2019-12-01 01:22:56
I have below code snap with Java 8. List<Employee> employees = DataProvider.getEmployees(); Set<Employee> set = employees.stream().filter(emp -> { System.out.println(emp.getName()); return emp.getName().equals("Vishal"); }).collect(Collectors.toSet()); I just want to know which implementation of Set it is using by default when we use Collectors.toSet() (refer above example)? Also, is there any way to tell the Java API to use a particular implementation (for example, HashSet )? The toSet() collector does not specify which implementation it uses; you get a Set , that's all. If you want a