0

I have the below method that I would like to rewrite using streams.

I was thinking to write a method and call that using stream().forEach() but not sure on how to map the return.

List<Student> students  = new ArrayList<>();
        if(myService.getData()!=null){
           for(Person person: myService.getData().getPersons()) {
               Student student = new Student();
               student.setGender(person.getSex());
               student.setGpa(person.getScore);
               students.add(student);
           }
        }
3
  • Honestly, using Streams will not improve this code. I would leave it as it is. Commented Jan 18, 2021 at 19:41
  • @VGR I completely agree. Just that I want to make the code look cleaner. :) Commented Jan 18, 2021 at 19:48
  • I’m pretty sure it will look cleaner as you have it, than any Stream-based solution could look. Commented Jan 18, 2021 at 19:53

1 Answer 1

1

You can use Optional and then use the constructor to create Student object

public Student(String sex, Integer score)  {
  this.sex = sex;
  this.score = score;
}

And then stream the Person list to create Student

List<Student> students = Optional.ofNullable(myService.getData())
        .map(data->data.getPersons().stream().map(per->new Student(per.getSex(),per.getScore())).collect(Collectors.toList())
        .orElse(Collections.emptyList();

You can also add null check for getPersons()

List<Student> students = Optional.ofNullable(myService.getData())
        .filter(data->data.getPersons()!=null)
        .map(data->data.getPersons().stream().map(per->new Student(per.getSex(),per.getScore())).collect(Collectors.toList())
        .orElse(Collections.emptyList();
Sign up to request clarification or add additional context in comments.

2 Comments

You don't really need an Optional here. The stream section could just replace the block within the if.
Since the stream operation doesn’t specify to return an ArrayList, there is no point in using ArrayList in the fallback case. Just use Collections.emptyList() instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.