java-stream

How to get a List<E> from a HashMap<String,List<E>>

余生长醉 提交于 2019-12-03 10:50:17
问题 I want to extract a List<E> from a Map<String,List<E>> ( E is a random Class) using stream() . I want a simple one-line method using java 8's stream. What I have tried until now : HashMap<String,List<E>> map = new HashMap<>(); List<E> list = map.values(); // does not compile list = map.values().stream().collect(Collectors.toList()); // does not compile 回答1: map.values() returns a Collection<List<E>> not a List<E> , if you want the latter then you're required to flatten the nested List<E> into

Why is the combiner of the Collector interface not consistent with the overloaded collect method?

六眼飞鱼酱① 提交于 2019-12-03 10:48:06
There is an overload method, collect() , in interface Stream<T> with the following signature: <R> R collect(Supplier<R> supplier, BiConsumer<R,? super T> accumulator, BiConsumer<R,R> combiner) There is another version of collect(Collector<? super T,A,R> collector) , which receives an object with the previous three functions. The property of the interface Collector corresponding to the combiner has the signature BinaryOperator<A> combiner() . In the latter case, the Java API 8 states that: The combiner function may fold state from one argument into the other and return that, or may return a new

“Good” method to call method on each object using Stream API

痴心易碎 提交于 2019-12-03 10:39:33
Is it possible to run a method, in a consumer, like a method reference, but on the object passed to the consumer: Arrays.stream(log.getHandlers()).forEach(h -> h.close()); would be a thing like: Arrays.stream(log.getHandlers()).forEach(this::close); but that's not working... Is there a possibility with method references, or is x -> x.method() the only way working here? You don't need this . YourClassName::close will call the close method on the object passed to the consumer : Arrays.stream(log.getHandlers()).forEach(YourClassName::close); There are four kinds of method references ( Source ):

Java 8 stream to file [duplicate]

我与影子孤独终老i 提交于 2019-12-03 10:32:28
问题 This question already has an answer here : Modify file using Files.lines (1 answer) Closed 4 years ago . Suppose I have a java.util.stream.Stream of objects with some nice toString method: What's the shortest/most elegant solution to write this stream to a file , one line per stream element? For reading, there is the nice Files.lines method, so I thought there must be a symmetric method for writing to file, but could not find one. Files.write only takes an iterable. 回答1: Probably the shortest

Using a stream to iterate n times instead of using a for loop to create n items

最后都变了- 提交于 2019-12-03 10:32:27
问题 Say I want to create n items. Pre Java 8, I would write: List<MyClass> list = new ArrayList<>(); for (int i = 0; i < n; i++) { list.add(new MyClass()); } Is there an elegant way to use a stream to create n items? I thought of this: List<MyClass> list = Stream.iterate(0, i -> i).limit(10) .map(o -> new MyClass()).collect(Collectors.toList()); Is there a standard/better way of coding this? Note that the actual usage is a bit more complex and using a stream would be more flexible because I can

Streams in Java, can't figure this code out

Deadly 提交于 2019-12-03 10:29:35
I've found the following code snippet: Function<Integer, Predicate<Integer>> smallerThan = x -> y -> y < x; List<Integer> l = Arrays.asList(5, 6, 7, 23, 4, 5645, 6, 1223, 44453, 60182, 2836, 23993, 1); List<Integer> list2 = l.stream() .filter(smallerThan.apply(l.get(0))) .collect(Collectors.toList()); System.out.println(list2); As output I receive: [4, 1] How does the smallerThan function in this example work, considering that we only pass one parameter smallerThan.apply(l.get(0)) ? Eran smallerThan is a Function that accepts a single Integer and returns a Predicate<Integer> (a Predicate

Java 8 lambda get and remove element from list

China☆狼群 提交于 2019-12-03 10:22:47
问题 Given a list of elements, I want to get the element with a given property and remove it from the list. The best solution I found is: ProducerDTO p = producersProcedureActive .stream() .filter(producer -> producer.getPod().equals(pod)) .findFirst() .get(); producersProcedureActive.remove(p); Is it possible to combine get and remove in a lambda expression? 回答1: To Remove element from the list objectA.removeIf(x -> conditions); eg: objectA.removeIf(x -> blockedWorkerIds.contains(x)); List<String

How to iterate nested lists with lambda streams?

試著忘記壹切 提交于 2019-12-03 10:11:40
I'm trying to refactor the following code to lambda expressions with `stream, especially the nested foreach loops: public static Result match (Response rsp) { Exception lastex = null; for (FirstNode firstNode : rsp.getFirstNodes()) { for (SndNode sndNode : firstNode.getSndNodes()) { try { if (sndNode.isValid()) return parse(sndNode); //return the first match, retry if fails with ParseException } catch (ParseException e) { lastex = e; } } } //throw the exception if all elements failed if (lastex != null) { throw lastex; } return null; } I'm starting with: rsp.getFirstNodes().forEach().?? // how

How can I use Java 8 Streams with an InputStream?

折月煮酒 提交于 2019-12-03 10:07:51
I would like to wrap a java.util.streams.Stream around an InputStream to process one Byte or one Character at a time. I didn't find any simple way of doing this. Consider the following exercise: We wish to count the number of times each letter appears in a text file. We can store this in an array so that tally[0] will store the number of times a appears in the file, tally[1] stores the number of time b appears and so on. Since I couldn't find a way of streaming the file directly, I did this: int[] tally = new int[26]; Stream<String> lines = Files.lines(Path.get(aFile)).map(s -> s.toLowerCase()

Turn linked Objects into Stream or Collection

∥☆過路亽.° 提交于 2019-12-03 09:58:06
I want to iterate over a stacktrace. The stacktrace consists of throwables whose getCause() returns the next throwable. The last call to getCause() returns null. (Example: a -> b -> null) I've tried to use Stream.iterable() which results in a NullPointerException, since the elements in the iterable can't be null. Here is a short demonstration of the problem: public void process() { Throwable b = new Throwable(); Throwable a = new Throwable(b); Stream.iterate(a, Throwable::getCause).forEach(System.out::println); } I'm currently using a while loop to create a collection manually: public void