Assume that there are below set of ball buckets:
BallBucket1 = Color=RED, BallCount=10
BallBucket2 = Color=RED, BallCount=5
BallBucket3 = Color=GREEN, BallCount=10
Now I want to put these ball in a rack, here I want all ball of RED color in one section of rack and balls of GREEN color in another section of the same rack.
I have written below code which solves my problem but, here I want to create externally map and fill it in pick() operation. I wanted to know if there is any terminal operation which can do the same task for me (something like Collectors.toMap())
package com.test;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
class BallBucket{
String color;
int count;
public BallBucket(String color, int count) {
super();
this.color = color;
this.count = count;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
public class TestStreams {
public static void main(String[] args) {
List<BallBucket> bucket = new ArrayList<BallBucket>();
bucket.add(new BallBucket("RED", 10));
bucket.add(new BallBucket("RED", 5));
bucket.add(new BallBucket("GREEN", 10));
Map<String, Integer> ballRack = new HashMap<String, Integer>();
bucket.stream()
.peek(ballBucket->{
ballRack.compute(ballBucket.color, (key,val)->val==null? ballBucket.count:val+ballBucket.count);
}).count();
System.out.println(ballRack);
}
}
output: {RED=15, GREEN=10}