java-stream

Files.newDirectoryStream vs. Files.list

十年热恋 提交于 2019-12-04 04:36:09
I am aware that Files.list(Path) uses Files.newDirectoryStream(Path) internally and basically just wraps the DirectoryStream. However I don't understand, when I want to use the first or the latter one. Is this just a convenience method, if I want to use the streaming API? I could have done this fairly easy myself, see this question . If one looks at the implementation of Files.list , exceptions thrown by the internal DirectoryStream are wrapped in UncheckedIOException . Anything I should know about this? This is in general a matter of style. If you want to use external iteration ( for(Path

Get object with max frequency from Java 8 stream

若如初见. 提交于 2019-12-04 04:25:38
I have an object with city and zip fields, let's call it Record . public class Record() { private String zip; private String city; //getters and setters } Now, I have a collection of these objects, and I group them by zip using the following code: final Collection<Record> records; //populated collection of records final Map<String, List<Record>> recordsByZip = records.stream() .collect(Collectors.groupingBy(Record::getZip)); So, now I have a map where the key is the zip and the value is a list of Record objects with that zip . What I want to get now is the most common city for each zip .

Is there something like Java Stream's “peek” operation in Scala?

混江龙づ霸主 提交于 2019-12-04 04:20:30
In Java you can call peek(x -> println(x)) on a Stream and it will perform the action for each element and return the original stream, unlike foreach which is Unit. Is there something similar in Scala, ideally something which works on all Monady types, allowing you to "pass through" the original Monad while performing a side effect action? (Logging, e.g.) It is of course easily implemented: def tap[A, U](a: A)(action: (A) => U): A = { action(a) a } but I'm hoping for something a bit more elegant or idiomatic. One way to solve this is using implicits: class Tappable[A](a: A) { def tap[U](action

Lambda expression for supplier to generate IntStream

倖福魔咒の 提交于 2019-12-04 04:16:47
How do I replace the Supplier code here with lambda expression IntStream inStream = Stream.generate(new Supplier<Integer>() { int x= 1; @Override public Integer get() { return x++ ; } }).limit(10).mapToInt(t -> t.intValue()); inStream.forEach(System.out::println); The output of above piece of code is: 1 2 3 4 5 6 7 8 9 10 Something like this if you're bound to use Stream.generate specifically : IntStream inStream = Stream.generate(new AtomicInteger(1)::getAndIncrement) .limit(10) .mapToInt(t -> t); inStream.forEach(System.out::println); Edit : Using IntStream.generate , you can perform it as

Returning stream rather than list [duplicate]

ⅰ亾dé卋堺 提交于 2019-12-04 04:08:52
This question already has answers here : Closed 4 years ago . Should I return a Collection or a Stream? (8 answers) In Java 8 I am increasingly replacing Collection return values with Stream . So where I would once have had: public List<Element> getElementList() { return elements; } I am now using: public Stream<Element> streamElements() { return elements.stream(); } My arguments for this are: It enforces the immutability of the underlying list It hides the fact that there is an underlying list. It could later be changed to a set or some other structure without changing the method signature.

Encounter order friendly/unfriendly terminal operations vs parallel/sequential vs ordered/unordered streams

蓝咒 提交于 2019-12-04 03:43:31
Inspired by this question , I started to play with ordered vs unordered streams, parallel vs sequential streams and terminal operations that respect encounter order vs terminal operations that don't respect it. In one answer to the linked question, a code similar to this one is shown: List<Integer> ordered = Arrays.asList( 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4, 4, 3, 2, 1, 1, 2, 3, 4); List<Integer> result = new CopyOnWriteArrayList<>(); ordered.parallelStream().forEach(result::add); System.out.println(ordered); System.out.println(result); And the lists are indeed different. The unordered list

Java 8 java.util.stream.Streams

爷,独闯天下 提交于 2019-12-04 03:29:12
I see many blog posts mention a Streams class and I see it was once part of the lambda branch API . It appears to be non-public API now and it does not match the previous implementation . Is there a different way to do Streams.concat() or to append multiple values to a stream? The Streams class got split and some of its methods were moved to StreamSupport , which does not contain a concat method in the latest build. The rationale for the split is explained here . The specific case of concat has been mentioned separately in this post where it was proposed for removal and was apparently removed.

Java 8 stream.collect( … groupingBy ( … mapping( … reducing ))) reducing BinaryOperator-usage

妖精的绣舞 提交于 2019-12-04 03:21:49
I played around with a solution using groupingBy , mapping and reducing to the following question: Elegantly create map with object fields as key/value from object stream in Java 8 . Summarized the goal was to get a map with age as key and the hobbies of a person as a Set . One of the solutions I came up with (not nice, but that's not the point) had a strange behaviour. With the following list as input: List<Person> personList = Arrays.asList( new Person(/* name */ "A", /* age */ 23, /* hobbies */ asList("a")), new Person("BC", 24, asList("b", "c")), new Person("D", 23, asList("d")), new

Detect duplicated groups in stream

天大地大妈咪最大 提交于 2019-12-04 03:18:54
I want to ensure that all numbers in the list are grouped together. Let me explain this on examples: {1, 1, 1, 2, 2} // OK, two distinct groups {1, 1, 2, 2, 1, 1} // Bad, two groups with "1" {1, 2, 3, 4} // OK, 4 distinct groups of size 1 {1, 1, 1, 1} // OK, 1 group {3, 4, 3} // Bad, two groups with "3" {99, -99, 99} // Bad, two groups with "99" {} // OK, no groups Here's how I obtain the stream: IntStream.of(numbers) ... Now I need to pass or return true for "OK" examples and throw AssertionError or return false on "Bad" examples. How can I do that using Stream API? Here's my current solution

Generating a short[] using streams

穿精又带淫゛_ 提交于 2019-12-04 03:16:33
Building upon Populating a List with a contiguous range of shorts I tried generating an array of primitive shorts. This turned out to be surprisingly harder than expected. Short[] range = IntStream.range(0, 500).mapToObj(value -> (short) value).toArray(Short[]::new) worked but: short[] range = IntStream.range(0, 500).mapToObj(value -> (short) value).toArray(short[]::new) generated a compiler error: method toArray in interface Stream<T> cannot be applied to given types; required: IntFunction<A[]> found: short[]::new reason: inference variable A has incompatible bounds equality constraints: