This question already has answers here:
Zipping streams using JDK8 with lambda (java.util.stream.Streams.zip)
(14 answers)
Is there an accepted Java equivalent to Python's zip()? [duplicate]
(1 answer)
Closed 5 years ago.
Say I have two streams:
Stream<String> ids = Stream.of("id1","id2","id3","id4","id5");
Stream<MyObj> objects = Stream.of(new MyObj(null, "some data"), new MyObj(null, "some other data");
Now I would like to update my objects stream with the data from ids. The result whould be equivalent to the following Stream:
Stream<MyObj> objects = Stream.of(new MyObj("id1", "some data"), new MyObj("id2", "some other data");
I thus wonder if there is a way to consume both streams, one element at the time. I imagine some kind of "DoubleConsumer" (nothing to do with double) of the sort:
Stream<MyObj> result = DoubleConsumer.of(ids, objects)
.map((id, myobj) -> combine(id, myobj));
MyObj combine(String id, MyObj myobj) {
myobj.set(id);
return myobj;
}
Any idea how to achieve something like this?
Update
I know that I can solve this in the case of list with some double loop, or with FuncionalJava's zipfunction. However the question is how to do this with Java Streams.
Do you want Stream.map. eg.
Stream<MyObj> objs = ids.map(id->new MyObj(id, "some data"));
This does exactly what op wants. Then if they want to update the values of the objects they can afterwards, and the objects know their id so that can be gotten.
If they want to "zip" two streams, they should check the existing answers.
Related
This question already has answers here:
Is there a concise way to iterate over a stream with indices in Java 8?
(24 answers)
Closed 3 years ago.
I am trying to iterate over a list of maps in java, but I can not figure it out how. I need to keep the index as well.
for example, I have a list of maps like
List<Map<String, String>> ListOfMaps = new ArrayList<>();
and the output that I want is something like:
"ListOfMaps[index].map(k) => ListOfMaps[index].map(k).getValue()"
I appreciate if you can give me some hint how I can do it using java stream operators, with high performance.
As an advocate for streams, I personally don't like using them here. But I will anyhow:
IntStream.range(0, mapList.size())
.forEach(index -> {
Map<String, String> map = mapList.get(index);
System.out.println("ListOfMaps[" + index + "]" ...);
})
This question already has an answer here:
Java equivalent for Python pool.map/ Multiprocessing
(1 answer)
Closed 4 years ago.
I know there have been questions which are similar to mine. However, they seem very outdated (assuming JDK 7, etc.)
So, I've been programming python for a while and had to learn Java for university.
I know that there is a feature in Python, where you can use a pool of Threads/Processes for mapping a list of values to a function.
from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)
I have to use the function on a large set of files and I have to use Java (10) and I want to use multiprocessing.
My question is: Does Java have such a feature? If so, whats the best practice to use it properly?
Yes, you can use parallelStream, for example, convert integer list to string list:
List<Integer> list = List.of(1, 2);
List<String> strings =
list.parallelStream()
.map(integer -> String.valueOf(integer)).collect(Collectors.toList());
This question already has answers here:
How can I turn a List of Lists into a List in Java 8?
(12 answers)
Closed 5 years ago.
Imaging object with following method:
class A { List<B> getIds(){...} }
Now I have an Collection of A as input;
And I want to get set of unique Ids out of it, normally you would go for:
Set<B> ids = new HashSet<>();
for(A a : input){
ids.addAll(a.getIds());
}
Is there a way to do the same in one line using stream API, like following
Set<List<B>> set = input.stream().map((a) -> a.getIds()).collect(Collectors.toSet());
but making flat set of B
You have to use flatMap
input.stream()
.map(a -> a.getIds())
.flatMap(ids -> ids.stream())
.collect(Collectors.toSet());
This will produce flat Set.
This question already has an answer here:
Partition java streams in categories [duplicate]
(1 answer)
Closed 5 years ago.
This question is a sort-of follow-up to Partition java streams in categories
I have a stream<A>, where
class A {
String category();
String data();
}
I would like to get a map<String, list<String>>, where the original stream is partitioned into sublists based on the value of category(), and then mapped to only extract the data(). It is pretty trivial to have it implemented using a for loop, but is it possible to get a more elegant solution harnessing java streams?
EXAMPLE:
Given {[a, xyz], [a, zyx], [b, abc]}, I would like to get a map:
a -> {xyz, zyx}
b -> {abc}
You need a slightly different groupBy
stream.collect(Collectors.groupingBy(A::getCategory,
Collectors.mapping(A::data, Collectors.toList()));
This question already has answers here:
Java 8 Stream IllegalStateException: Stream has already been operated on or closed
(6 answers)
Closed 6 years ago.
I need to calculate the ratio of two parts of the big List, wherein the first part contains the second:
Stream<Element> part1 = list.stream().filter(x -> x.getN1() < x.getN2);
int result = part1.filter(y -> y.isRight()).count() / part1.count();
But this code throws the Exception: java.lang.IllegalStateException: stream has already been operated upon or closed
Can I write a code without creating the same part1 stream in result?
You can only reuse a collection as it has memoriation of results.
List<Element> part1 = list.stream().filter(x -> x.getN1() < x.getN2).collect(toList());
double result = (double) part1.stream().filter(y -> y.isRight()).count() / part1.size();
A Stream is a builder for some code which is optimised at run time. It's execution isn't as dynamic as it appears.
Streams are not supposed to be reused, or if you want something seemed to it, you can use suppliers as mentioned here : Copy a stream to avoid "stream has already been operated upon or closed" (java 8)