简体   繁体   中英

How to write java streams for the nested loops

How do I use the java streams for the below scenario with nested loops...

package test;
import java.util.ArrayList;
import java.util.List;
import lombok.Getter;
import lombok.Setter;

@Setter
@Getter
class Car {
  String carName;
  int wheelNo;
  WheelDetails wheelDetails;

  Car(String carName, int wheelNo) {
    this.carName = carName;
    this.wheelNo = wheelNo;
  }
}

@Getter
@Setter
class WheelDetails {
  int wheelNo;
  String wheelColour;
  int Size;

  WheelDetails(int wheelNo, String wheelColour, int Size) {
    this.wheelNo = wheelNo;
    this.wheelColour = wheelColour;
    this.Size = Size;
  }
}

public class testMain {

  public static void main(String[] args) {

    List<Car> cars = new ArrayList<Car>();
    cars.add(new Car("CarOne", 1));
    cars.add(new Car("CarTwo", 2));

    List<WheelDetails> wheelDetailsList = new ArrayList<WheelDetails>();
    wheelDetailsList.add(new WheelDetails(1, "Black", 16));
    wheelDetailsList.add(new WheelDetails(2, "Grey", 17));
    for (Car car : cars) {
      for (WheelDetails wheelDetails : wheelDetailsList) {
        if (car.getWheelNo() == wheelDetails.getWheelNo()) {
          car.setWheelDetails(wheelDetails);
        }
      }
    }
  }
}

not able to find the options to do the above in the streams it will be great helpful

have gone trough the other areas but could not find it... any link or solution will be helpful......

The following solution modifies elements in the list of cars:

cars.forEach(car -> car.setWheelDetails(
    wheelDetailsList.stream()
                    .filter(wd -> car.getWheelNo() == wd.getWheelNo())
                    .findFirst()
                    .orElse(null)
));

Another faster solution is based on a temporary map <Integer, WheelDetails> :

Map<Integer, WheelDetails> wheelMap = wheelDetailsList
        .stream()
        .collect(Collectors.toMap(
            WheelDetails::getWheelNo, // key
            wd -> wd,                 // value
            (wd1, wd2) -> wd1,        // (optional) merge function to resolve conflicts
            LinkedHashMap::new        // keep insertion order
        ));
cars.forEach(car -> car.setWheelDetails(wheelMap.get(car.getWheelNo())));

Try this:

cars.forEach(car -> wheelDetailsList.stream()
    .filter(wheelDetails -> wheelDetails.wheelNo == car.wheelNo).forEach(car::setWheelDetails));

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