How to process the received List <T> `groupingBy` values ββin the same` stream () `?
In short: collect(groupingBy()) returns a map Map<K, List<T>> . How can I replace for each K value of List<T> with a new value (of class U ), which is calculated based on List<T> , and returns Map<K, U> in the same stream() ?
Example: Suppose I have a Task that consists of taskId and a list of Job s:
public class Task { int taskId; List<Job> jobList; } For each Job the getAgentId method defines an βagentβ that can process it:
// in class Job int getAgentId() { // return the "agent" who is responsible for @param job } A Task divided into several sub- Task , so that each of them can be processed by a separate "agent":
// in class Partition; `Integer` for "agent" id Map<Integer, Task> partition(Task task) { } My attempt: I used groupingBy :
Map<Integer, Task> partition(Task task) { int id = task.getTaskId(); Map<Integer, List<Job>> agentJobsMap = task.getJobList().stream() .collect(groupingBy(Job::getAgentId), // question here); } Question: However, I want to return Map<Integer, Task> instead of Map<Integer, List<Job>> ; those. I want to wrap the resulting List<Job> result from groupingBy in a new Task on a new Task(id, the resulting List<Job>) . How to do it? Or are there alternatives without groupingBy ?