#Java Streams but with a Map!
1 messages ยท Page 1 of 1 (latest)
Helper please have a look, thanks.
So in Java you have forEach so I have the following (Sorry I said streams)
Is there anyway to simplify this and put it into a Map?
You can use a collector to collect to a map
I saw this using somehting like a HashMap but unsure if I have to just double loop it anyway
and then loop the Map
I don't think u can directly set them to a map
hi there
Hello
i think the way you mentioned is already simplified
your purpose is to loop through a collection
and in each element, you call a field (which is a collection too)
and perform an operation on it
It just double loops it which looks abit bad
And I only need the second loop
Well I need both but the second one is where its using it
hmm maybe you can use flatMap
Tried that seems u need to loop twice anyway
how did you do ?
Flatmap with an inner stream should work
Yes you can
repita.stream().flatMap(rep -> rep.getReppo()).forEach(rapo -> doSomething(repoo, rapo))
but how is it accessing the repoo
Like how is it getting the current repoo to get the information
use peek()
like this :
repita.stream()
.flatMap(rep -> rep.getRepo().stream().peek(rapo -> doSomething(rep, rapo)))
.toList();
it should work
Sweet let me try
well im not sure this is the right way actually ๐ค
With a HashMap of both Objects?
Oh that would just go back to the first issue haha I might as well do 2 forEach
yeah i think that one was fine. and to em it's not double loop
it's a nested loop
ok
repita
.stream()
.flatMap(rep -> rep.getReppo().stream().map(rapo -> new SimpleEntry<>(rep, rapo)))
.forEach(entry -> doSomething(entry.getKey(), entry.getValue()))
i think this also works, but it's longer
The SimpleEntry object helps create key value objects
then in forEach you call that method
this did work for me :
class Scratch {
public static void main(String[] args) {
Set<Bucket> buckets = Set.of(
new Bucket(Set.of(new BucketItem(), new BucketItem(), new BucketItem())),
new Bucket(Set.of(new BucketItem(), new BucketItem(), new BucketItem())),
new Bucket(Set.of(new BucketItem(), new BucketItem(), new BucketItem()))
);
List<BucketItem> list = buckets.stream()
.flatMap(bucket -> bucket.items()
.stream()
.peek(bucketItem -> System.out.println(bucketItem.toString() + bucket.toString())))
.toList();
}
}
record Bucket(UUID uuid, Set<BucketItem> items) {
Bucket(Set<BucketItem> items) {
this(UUID.randomUUID(), items);
}
}
record BucketItem(UUID uuid) {
BucketItem() {
this(UUID.randomUUID());
}
}
Sweet I will try this
wdym, in your original code, repoo isn't declared anywehere, so I though that it was a local varibale
please don't use peek @distant trail
Okay...
Its inside the List
List<ObjectName>
Inside this object there is other objects
List<BucketItem> list = buckets.stream()
.flatMap(bucket -> bucket.items()
.stream()
.toList();