#BAEL-18410 add code sample for reduce with complex objects

This commit is contained in:
Alessio Stalla
2019-11-09 15:06:10 +01:00
parent 12962fb016
commit bb7c57f428
5 changed files with 101 additions and 1 deletions

View File

@@ -0,0 +1,39 @@
package com.baeldung.streamreduce.entities;
import java.util.ArrayList;
import java.util.List;
public class Rating {
double points;
List<Review> reviews = new ArrayList<>();
public Rating() {}
public void add(Review review) {
reviews.add(review);
computeRating();
}
private double computeRating() {
double totalPoints = reviews.stream().map(Review::getPoints).reduce(0, Integer::sum);
this.points = totalPoints / reviews.size();
return this.points;
}
public static Rating average(Rating r1, Rating r2) {
Rating combined = new Rating();
combined.reviews = new ArrayList<>(r1.reviews);
combined.reviews.addAll(r2.reviews);
combined.computeRating();
return combined;
}
public double getPoints() {
return points;
}
public List<Review> getReviews() {
return reviews;
}
}

View File

@@ -0,0 +1,28 @@
package com.baeldung.streamreduce.entities;
public class Review {
int points;
String review;
public Review(int points, String review) {
this.points = points;
this.review = review;
}
public int getPoints() {
return points;
}
public void setPoints(int points) {
this.points = points;
}
public String getReview() {
return review;
}
public void setReview(String review) {
this.review = review;
}
}

View File

@@ -4,6 +4,7 @@ public class User {
private final String name;
private final int age;
private final Rating rating = new Rating();
public User(String name, int age) {
this.name = name;
@@ -17,7 +18,11 @@ public class User {
public int getAge() {
return age;
}
public Rating getRating() {
return rating;
}
@Override
public String toString() {
return "User{" + "name=" + name + ", age=" + age + '}';