0

Stream instead of nested forEach loops

I'd like to use stream instead of nested forEach loop. I tried to create stream as seen below but it doesn't work. ForEach loops work fine. List of CarWrapper objects should contain as many objects as each of Car objects has strings in its strings list. Could you help?

'''

class Main {
 public static void main(String[] args) {
  new doit();
 }
}

class doit{
 public doit(){
List<CarWrapper> wrappers;
List<Car> cars = new ArrayList<>();
cars.add(new Car());
cars.add(new Car());

  //  cars.forEach(car -> {
  //         car.getDriver().getStrings().forEach(string -> {
  //             wrappers.add(wrapper(car, string));
  //         });
  //     });

  wrappers = cars.stream()
  .map(car->{
     car.getDriver().getStrings().forEach(string->{
      wrapper(car, string);
    });
  })
  .collect(Collectors.toList());
}


 public CarWrapper wrapper(Car car, String s){
   return new CarWrapper.Builder().setBrand(car.getBrand()).setString(s).build();
  }
}


  class Car{
    private Driver driver;
    private String brand;

  public Car(){
     this.brand="bmw";
     this.driver = new Driver();
  }

   public Driver getDriver(){
     return driver;
   }

   public String getBrand(){
     return brand;
    }
   }

   class Driver{
   private List<String> strings;

   public Driver(){
     this.strings = Arrays.asList("qwe","zxc");
   }

    public List<String> getStrings(){
     return strings;
     }
    }

  class CarWrapper{ 
    private String brand;
    private String string;

    private CarWrapper(){
    }

  public static class Builder{
  private String brand;
  private String string;

  public Builder setBrand(String brand){
    this.brand=brand;
    return this;
  }
  public Builder setString(String string){
    this.string=string;
    return this;
  }
  public CarWrapper build(){
    CarWrapper carWrapper = new CarWrapper();
    carWrapper.brand = this.brand;
    carWrapper.string = this.string;
    return carWrapper;
  }
}
}

'''

3
  • What did the non-stream version look like? Commented Jun 27, 2020 at 10:57
  • 1
    @Andreas I believe it's the commented-out part of the code. Commented Jun 27, 2020 at 10:58
  • @Sweeper Ohh, I was looking for old style for-each loops like for (car : cars) Commented Jun 27, 2020 at 11:00

1 Answer 1

4

Try this

wrappers = cars.stream()
              .flatMap(car -> car.getDriver().getStrings().stream()
                      .map(string -> wrapper(car, string)))
              .collect(Collectors.toList());
Sign up to request clarification or add additional context in comments.

Comments

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.