![](/img/trans.png)
[英]how execute if condition several times without break inside for loop in java?
[英]How to modify an object with condition inside a list without a loop in Java 7
I want to change some of the object properties inside a list without any loop in efficient way in Java 7 , since in Java 8 we can use stream, please don't refer to any third party library like Guava, because i can't add公司旧系统的任何新库。
MenuResponse.java
public class MenuResponse {
String id;
String title;
String type;
// Getters and setters omitted for brevity
}
MenuService.java
public List<MenuResponse> getMenu() {
List<MenuResponse> data = new ArrayList<>();
/* sample local data */
MenuResponse a = new MenuResponse();
a.setId("1");
a.setTitle("Time Deposit");
a.setType("OK");
MenuResponse b = new MenuResponse();
b.setId("2");
b.setTitle("Account");
b.setType("OK");
MenuResponse c = new MenuResponse();
c.setId("3");
c.setTitle("Submission Wizard");
c.setType("DISABLED");
data.add(a);
data.add(b);
data.add(c);
/* here i want to alter the title menu to "Under Maintenance" if type = 'DISABLED' */
/* this is my best in Java 8 */
Optional<MenuResponse> dd = data.stream()
.filter(menu -> menu.getType().equalsIgnoreCase("DISABLED"))
.findFirst();
if(dd.isPresent()){
dd.get().setTitle("Under Maintenance");
}
return data;
}
客观的
基于上面的代码片段,我想更新一些数组 object 属性,在这种情况下,我想将 MenuResponse 的标题更改为“维护中”,以防类型等于“禁用”,但没有任何循环。
任何帮助和解释将不胜感激,谢谢
您可以使用peek()
function:
data.stream()
.filter(menu -> menu.getType().equalsIgnoreCase("DISABLED"))
.peek(menuResponse -> menuResponse.setTitle("Under Maintenance"))
.collect(Collectors.toList());
与map()
function:
data.stream()
.filter(menu -> menu.getType().equalsIgnoreCase("DISABLED"))
.map(menuResponse -> {
menuResponse.setTitle("Under Maintenance");
return menuResponse;
})
.collect(Collectors.toList());
它不是很有效(因为整个列表都是排序的),而且看起来很奇怪,但它没有循环和流:)
// 1. Let's sort list by type, ascending.
Collections.sort(data, new Comparator<MenuResponse>(){
@Override
public int compare(MenuResponse o1, MenuResponse o2) {
return o1.getType().compareTo(o2.getType());
}
});
// DISABLED
// OK
// OK
// 2. Let's update title of DISABLED element
if (data.size()>0 && data.get(0).getType().equalsIgnoreCase("DISABLED")) {
data.get(0).setTitle("Under Maintenance");
}
实现它的一种方法是在MenuResponse
中重写equals()
(建议同时重写hashCode()
),只需type
如下:
@Override
public int hashCode() {
return Objects.hash(type);
}
@Override
public boolean equals(Object obj) {
if (obj == null)
return false;
MenuResponse other = (MenuResponse) obj;
return Objects.equals(type, other.type);
}
然后,您可以删除第一次出现的 object,其类型为DISABLED
,如下所示:
MenuResponse o = new MenuResponse();
o.setType("DISABLED");
int index = data.indexOf(o);
if (index != -1) {
data.remove(index);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.