I am having two lists of Strings and want to compare the values in the lists and construct a new list of another object. I am able to do this with nested loops but looking for a more performant and neater solution.
List<String> list1 = new ArrayList();
list1.add("A,Airplane");
list1.add("B,Boat");
List<String> list2 = new ArrayList();
list2.add("A90, Boing Airplane");
list2.add("A70, Boing777");
list2.add("B80, Boing Boat");
There is a Vehicle object.
class Vehicle {
private String model;
private String submodel;
private String type;
private String subtype;
// setters getters
}
Now, I need to build the vehicle object using by matching the model (the first character from list1) with the first character in list2 and build something like this
private List<Vehicle> buildVehicle(List<String> list1, List<String> list2) {
List<Vehicle> vehicles = new ArrayList<>();
if (ObjectUtils.isNotEmpty(list2)) {
list2.forEach(v -> {
Vehicle vehicle = new Vehicle();
if (v.contains(",")) {
String[] val = StringUtils.split(v,",");
vehicle.setSubtype(val[0]);
vehicle.setSubmodel(val[1]);
}
for (String c : list1) {
//Matching the first character from element in list1
if (c.substring(0,1).equals(vehicle.getSubtype().substring(0,1))
&& c.contains(",")) {
String[] val = StringUtils.split(c, ",");
vehicle.setType(val[0]);
vehicle.setModel(val[1]);
}
break;
}
}
vehicles.add(vehicle);
});
}
return vehicles;
}
Can the nested loop be avoided by using streams?
ObjectUtilsandStringUtilsare not part of the JDK.