[英]mybatis - nulls are removed in HashMap<String, Object> result
[英]String containing all object properties with no nulls
我在構造函數中得到了這些對象。
cars.add(new Car(2016, "honda", "civic"));
cars.add(new Car(2017, "Lamborghini", "aventador"));
cars.add(new Car(2000, null, "caravan"));
cars.add(new Car(2010, "dodge", null));
我需要以下列格式返回其中的所有數據:hondacivicLamborghiaventadorcaravandodge
我的 function 是:
public String listAllCars()
{
String result;
result = null;
if(cars == null)
{
throw new IllegalArgumentException("c cannot be null");
}
for(Car car: cars)
{
if(car.getMake() != null || car.getModel() != null)
{
result += car.getMake() + car.getModel();
}
}
return result;
}
但我最終得到nullhondacivicLamborghiniaventadornullcaravandodgenull
而不是hondacivicLamborghiniaventadorcaravandodge
。
您正在檢查 make 或 model 中的任何一個是否不是 null。 但是,您的情況要求您分別檢查 make 和 model 並連接(如果存在)。
for(Car car: cars) {
if(car.getMake() != null) { result += car.getMake(); }
if(car.getModel() != null) { result += car.getModel(); }
}
如果不是獨立的null
,則需要 append 每個字段。 為了緊湊,您可以使用Objects.toString
。 為了效率,一個簡單的if
就可以了。
如果您可以使用 Streams API:
public String listAllCars() {
if (cars == null) {
throw new IllegalArgumentException("c cannot be null");
}
return cars.stream()
.map(c -> Objects.toString(c.getMake(), "")
+ Objects.toString(c.getModel(), ""))
.reduce("", (a, b) -> a + b);
}
或者,使用命令式風格,但使用StringBuilder
:
public String listAllCars() {
if (cars == null) {
throw new IllegalArgumentException("c cannot be null");
}
StringBuilder result = new StringBuilder();
for (Car car : cars) {
result.append(Objects.toString(car.getMake(), ""));
result.append(Objects.toString(car.getModel(), ""));
}
return result.toString();
}
或者,沒有StringBuilder
:
public String listAllCars() {
if (cars == null) {
throw new IllegalArgumentException("c cannot be null");
}
String result = "";
for (Car car : cars) {
result += Objects.toString(car.getMake(), "");
result += Objects.toString(car.getModel(), "");
}
return result;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.