简体   繁体   中英

Iterate java nested list using Java8 Stream

I have a Java list of EmployObject like this

List<Employee> emp = {emp1, emp2, emp3, emp4 ,...}

Where the Employee class looks like this 

Public Class Employee {
    String EmpId;
    EmpInfo empInfo;
}

public class EmpInfo {
   String salary;
   String address;
   List<Reviews> reviews;
}

public class Reviews {
   int ratings;
   boolean isGood;
}

I want to use Java8 streams to iterate a over the list (List emp) and filter EmpId which has more than one rating (List lenghth > 1) and whose rating is good (isGood == true). The new list will look like

List empRating = {empRating1, empRating2, ...}

public class EmpRating {
   String empId;
   int ratings;
}


I tried different things but not able to find out an optimized solution. Need help with this.

Just an example:

  • selecting employees who have at least one rating isGood
  • calculating sum of all ratings
employeeList.stream()
    .filter(emp -> emp.getEmpInfo().getReviews().size() > 1
                && emp.getEmpInfo().getReviews().stream().anyMatch(Reviews::isGood))
    .map(emp -> new EmpRating(
        emp.getEmpId(), 
        emp.getEmpInfo().getReviews().stream().mapToInt(Reviews::getRatings).sum()
    ))
    .collect(Collectors.toList());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM