英文:
Best way to write multiple or conditions on a object in JAVA
问题
有没有更简便的方法执行 `||` 和 `&&` 操作,或许可以使用 Java 8?
因为我还有一些其他类似于 `OrderSummaryService` 的类,它们还有一些其他字段。
@Getter
@Setter
class Orders
{
String id;
String status;
Items items;
String orderDate;
String createdBy;
String updatedBy;
Double amount;
}
@Getter
@Setter
class Items
{
String itemId;
String itemName;
String amount;
String quantity;
}
class OrderSummaryService
{
public static void main(String args[])
{
Orders orders = orderRepository.getOrderDetails();
if (orders.getStatus() != null || orders.getCreatedBy() != null
|| orders.getUpdatedBy() != null || orders.getAmount() != null
|| (orders.getOrderDate() != null && orders.getItems() != null))
{
OrderDetail details = orderRepository.updateRepository();
ItemDetail itemDetail = itemRepository.updateItem();
// 一些服务代码
}
}
}
英文:
Is there an easier way to perform ||
and &&
operations, maybe using Java 8?
As I have some other classes like OrderSummaryService
and it has some more fields.
@Getters
@Setters
class Orders
{
String id;
String status;
Items items;
String orderDate;
String createdBy;
String updatedBy;
Double amount;
}
@Getters
@Setters
class Items
{
String itemId;
String itemName;
String amount;
String quantity;
}
class OrderSummaryService
{
public static void main(String args[])
{
Orders orders = orderRepository.getOrderDetails();
if (orders.getStatus() != null || orders.getCreatedBy() != null
|| orders.getUpdatedBy() != null || orders.getAmount() != null
|| orders.getOrderDate() != null && orders.getItems() != null)
{
OrderDetail details = orderRepository.updateRepository();
ItemDetail itemDetail = itemRepository.updateItem();
// some service code
}
}
}
答案1
得分: 6
如果您打算在多个地方使用相同的逻辑,我会向Orders
类添加一个方法,例如:
public boolean isValidOrders() {
return status != null || createdBy != null || updatedBy != null
|| amount != null || orderDate != null && items != null;
}
英文:
If you're going to be using the same logic in multiple places, I would add a method to the Orders
class e.g.
public boolean isValidOrders() {
return status != null || createdBy != null || updatedBy != null
|| amount != null || orderDate != null && items != null;
}
答案2
得分: -1
你可以使用这段代码来替代||
链:
Stream.of(orders.getStatus(), orders.getCreatedBy(), /*其他部分*/).anyMatch(Objects::nonNull)
anyMatch
是短路求值的,类似于逻辑或操作。
英文:
You can use this to replace the chain of ||
s
Stream.of(orders.getStatus(), orders.getCreatedBy(), /*the others*/).anyMatch(Objects::nonNull)
anyMatch
is short-circuiting, works similar to a logical or
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论