user1298426 :
Mapping one object to another with aggregation and grouping
I have a class
class Q {
String username;
int taskId;
double timediff;
// constructor
}
and I need to convert it to
class ToQ {
String username;
int noOfTasks;
double sum;
// constructor
}
So the intension is group by username, count no of taskIds, sum of timediff.
List of this
List<Q> qs = new ArrayList<>();
qs.add(new Q("tom", 2, 2.0));
qs.add(new Q("tom", 6, 1.0));
qs.add(new Q("harry", 8, 0.03));
Should have output of ToQ as
new ToQ("tom",2,3);
new ToQ("harry",1,0.03);
I tried with grouping function but it generates HashMap but not sure how to convert into object.
Map<String, Double> collect = qs
.stream()
.collect(groupingBy(Q::getUsername, summingDouble(Q::getLocalDateTime)));
Naman :
Form a
You could do it as follows:
Group by Name for TimeDiff
Map<String, Double> nameToTimeDiffSumMap = qs.stream()
.collect(Collectors.groupingBy(Q::getUsername,
Collectors.summingDouble(Q::getTimediff)));
Group by Name for Count
Map<String, Long> nameToCountMap = qs.stream()
.collect(Collectors.groupingBy(Q::getUsername,
Collectors.counting()));
Form a List<ToQ>
List<ToQ> toQS = qs.stream().map(a ->
new ToQ(a.getUsername(), nameToCountMap.get(a.getUsername()), nameToTimeDiffSumMap.get(a.getUsername())))
.collect(toList());
which assumes the classes to have getters and setters and appropriate constructor as well
class ToQ {
String username;
long noOfTasks;
double sum;
}
class Q {
String username;
int taskId;
double timediff;
}