Use Java 8 Optional in existing Java 7 code

前端 未结 4 915
傲寒
傲寒 2021-01-06 20:22

I have an assignment in which I need to convert the following pre-Java 8 code to Java 8 code. Below is just one method which is giving me hard time to finish up:

         


        
4条回答
  •  梦谈多话
    2021-01-06 20:44

    If you really want to convert flow control to Optional, the code keep consistent with yours should be like this(I break the code in 2 lines for printing):

    public static Optional> loadMatchingJava8(Region region, 
                                                                String nameStartsWith,
                                                                VehicleLoader loader) {
        if ((nameStartsWith == null) || (region == null) || (loader == null)) {
            throw new IllegalArgumentException("The VehicleLoader and both region and " +
                    "nameStartsWith are required when loading VehicleMake matches");
        }
    
    
        return Optional.ofNullable(loader.getVehicleMakesByRegion(region.name()))
                .map(makers -> makers.stream()
                        .filter((it) -> it.getName() != null
                                && it.getName().startsWith(nameStartsWith))
                        .collect(Collectors.toList()));
    }
    

    NOTE: you can see more about why do not abuse Optional in this question.

提交回复
热议问题