java-stream

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

冷暖自知 提交于 2019-12-03 01:04:06
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 immediately pump the items through other functions in one line without even creating a reference to the

Java 8 stream to file [duplicate]

不想你离开。 提交于 2019-12-03 01:03:24
This question already has an answer here : Modify file using Files.lines (1 answer) 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. Tagir Valeev Probably the shortest way is to use Files.write along with the trick which converts the Stream to the Iterable : Files.write(Paths.get

Java 8 lambda get and remove element from list

爱⌒轻易说出口 提交于 2019-12-03 00:53:25
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? uma shankar To Remove element from the list objectA.removeIf(x -> conditions); eg: objectA.removeIf(x -> blockedWorkerIds.contains(x)); List<String> str1 = new ArrayList<String>(); str1.add("A"); str1.add("B"); str1.add("C"); str1.add("D");

Collectors.toMap() keyMapper — more succinct expression?

痴心易碎 提交于 2019-12-03 00:44:16
问题 I'm trying to come up with a more succinct expression for the "keyMapper" function parameter in the following Collectors.toMap() call: List<Person> roster = ...; Map<String, Person> map = roster .stream() .collect( Collectors.toMap( new Function<Person, String>() { public String apply(Person p) { return p.getLast(); } }, Function.<Person>identity())); It seems that I should be able to inline it using a lambda expression, but I cannot come up with one that compiles. (I'm quite new to lambdas,

Create only 1 list from a map where map value is list using JAVA 8 Streams

北城余情 提交于 2019-12-03 00:39:09
问题 I have a Map, where the "value" is a List of projects: Map<User, List<Project>> projectsMap = ... I want to extract from the map the projects but in only and just 1 List of projects: I've already seen answers but they don't apply to my case. I don't want this result: List<List<Project>> theValueOfTheMap; The result I want is: List<Project> projects = ... // All the project in the value's map How can I achieve this using JAVA 8 Streams? Thanks. Leonardo. 回答1: Thanks @Holger for the answer.

Java 8 Streams: How to call once the Collection.stream() method and retrieve an array of several aggregate values with different fields

谁说我不能喝 提交于 2019-12-02 23:48:38
I'm starting with the Stream API in Java 8. Here is my Person object I use: public class Person { private String firstName; private String lastName; private int age; private double height; private double weight; public Person(String firstName, String lastName, int age, double height, double weight) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.height = height; this.weight = weight; } public String getFirstName() { return firstName; } public String getLastName() { return lastName; } public int getAge() { return age; } public double getHeight() { return height; }

Java 8 stream operations execution order

天大地大妈咪最大 提交于 2019-12-02 23:46:05
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8); List<Integer> twoEvenSquares = numbers.stream().filter(n -> { System.out.println("filtering " + n); return n % 2 == 0; }).map(n -> { System.out.println("mapping " + n); return n * n; }).limit(2).collect(Collectors.toList()); for(Integer i : twoEvenSquares) { System.out.println(i); } when executed the logic below output came filtering 1 filtering 2 mapping 2 filtering 3 filtering 4 mapping 4 4 16 if the stream follows the short circuit concept (where we use limit stream operation), then output must be like below: filtering 1

Find the difference between two collections in Java 8?

风格不统一 提交于 2019-12-02 22:53:22
I am trying to make a List of all of the books in one Collection that are not present in another. My problem is that I need to compare based on book ID, so I can't just test to see whether a book in the first is contained in the second, I have to determine whether any book in the second collection has the same ID as a book in the first. I have the below code to compare two collections of books and filter the first collection: List<Book> parentBooks = listOfBooks1.stream().filter(book-> !listOfBooks2.contains(book)).collect(Collectors.toList()); The code doesn't work correctly because I am

Java 8 stream objects significant memory usage

▼魔方 西西 提交于 2019-12-02 22:27:57
In looking at some profiling results, I noticed that using streams within a tight loop (used instead of another nested loop) incurred a significant memory overhead of objects of types java.util.stream.ReferencePipeline and java.util.ArrayList$ArrayListSpliterator . I converted the offending streams to foreach loops, and the memory consumption decreased significantly. I know that streams make no promises about performing any better than ordinary loops, but I was under the impression that the difference would be negligible. In this case it seemed like it was a 40% increase. Here is the test

How does reduce() method work with parallel streams in Java 8?

懵懂的女人 提交于 2019-12-02 21:59:56
问题 I try to understand how reduce() method works exactly with parallel streams and I don't understand why the following code do not return the concatenation of these strings. This is the code: public class App { public static void main(String[] args) { String[] grades = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K"}; StringBuilder concat = Arrays.stream(grades).parallel() .reduce(new StringBuilder(), (sb, s) -> sb.append(s), (sb1, sb2) -> sb1.append(sb2)); System.out.println(concat); }