robert trudel
robert trudel

Reputation: 5749

Java stream none match multiple condition

In a dto to bean conversion,

I try to add dto only if dto is not found in the bean... or if the id of the dto is null

I use stream with none match.

When i try to add many car, only the first one is added

 List<Car> cars = bean.getCar();
 List<CarDto> carsDto = dto.getCar();

 for (CarDto carDto : carsDto) {

     if (cars.stream().noneMatch(e -> Objects.equals(e.getId(), carDto.getId()) || carDto.getId()==null )) {

        //get car from bd....

        bean.addCar(car);
    }

}

Upvotes: 2

Views: 2915

Answers (2)

Thiyagu
Thiyagu

Reputation: 17890

Having the condition carDto.getId()==null within noneMatch will prevent you from taking CarDto that have null id.

You can change it as

if (carDto.getId() == null 
         || cars
             .stream()
             .noneMatch(e -> Objects.equals(e.getId(), carDto.getId()))) 

UPDATE:

Thanks to Holger@ for this suggestion: You can simplify the second if condition as (and need not use Objects.equals since carDto.getId cannot be null.

cars.stream()
    .map(Car::getId)
    .noneMatch(carDto.getId()::equals)

Upvotes: 5

ernest_k
ernest_k

Reputation: 45309

You can also use the stream API fully without resorting to the imperative loop:

List<Car> cars = bean.getCar();
List<CarDto> carsDto = dto.getCar();

Set<String> carSet = cars.stream()
       .map(car -> car.getId()).collect(Collectors.toSet());

carsDto.stream()
       .filter(car -> car.getId() == null || !carSet.contains(car.getId()))
       .forEach(bean::addCar);

If Car is Comparable on id, you could also just use the carSet.contains(car) and avoid pre-creating the car ID set.

Upvotes: 2

Related Questions