英文:
How to get the filled field of java.util.Set <Object> or if the field is empty, return something else?
问题
我有一个 Addresses 类,在 Customer 类的两个属性中使用,第一个属性是一个简单的对象,用于表示客户的默认地址,另一个属性是一个包含可能存在的地址的 Set
我需要将 postalCode 字段发送到另一个类。我想在 Set
Optional.ofNullable(Stream.of(product.getCustomer().getAddresses())
.map(i -> i.getPostalCode())
.filter(Objects::nonNull)
.findFirst()
.orElse(product.getCustomer().getAddressDefault().getPostalCode()));
我的类如下:
public class Customer {
private Addresses addressDefault;
private Set<Addresses> addresses;
}
public class Addresses {
private String postalCode;
private String city;
private String state;
private String country;
}
英文:
I have an Addresses class that is used in two attributes of the Customer class, the first attribute is a simple object to represent the customer's default address and another attribute is a Set <> of addresses that the customer can have.
I need to send the postalCode field to another class. I would like to check in Set <> if there is a filled postalCode, if yes, send this value, otherwise (if there is no filled postalCode within Set <>) then I should send the postalCode value from the default address. How to do this? I tried this way before:
Optional.ofNullable(Stream.of(product.getCustomer().getAddresses()).forEach
(i -> i.getPostalCode())).orElse(product.getCustomer().getAddressDefault().getPostalCode()))
My classes bellow:
public class Customer {
private Addresses addressDefault;
private Set<Addresses> addresses;
}
public class Addresses {
private String postalCode;
private String city;
private String state;
private String country;
}
答案1
得分: 1
使用Java 8的流,您可以使用map
将地址转换为其postalCode
,使用filter
来删除null
值,并使用findFirst
来获取第一个非null的postalCode
。
Stream.findFirst
会通过返回一个Optional来处理空流。要获取其值或默认值,请使用Optional.orElse
方法。
在代码中:
String postalCode = customer.addresses.stream()
.map(addresses -> addresses.postalCode)
.filter(Objects::nonNull)
.findFirst()
.orElse(customer.addressDefault.postalCode);
英文:
Using Java 8 streams, you can use map
to transform an address to its postalCode
, use filter
to remove null
values, and use findFirst
to get the first non-null postalCode.
Stream.findFirst
deals with empty streams by returning an optional. To get its value or a default value, use the Optional.orElse
method.
In code:
String postalCode = customer.addresses.stream()
.map(addresses -> addresses.postalCode)
.filter(Objects::nonNull)
.findFirst()
.orElse(customer.addressDefault.postalCode);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论