我有一个列表,我正在迭代它,并且在每个元素的某些条件下,我将列表的每个元素添加到数据结构的特定位置,以下是Java 7中的代码。
我从列表中添加每个元素的数据结构是,
/* The data structure has two slots, one for parents and another for children */
MenuBar menuBar = new MenuBar();
现在的代码片段是,
MenuBar menuBar = new MenuBar();
for (Menu menu : menuList) {
if (isParentMenu(menu.getId())) {
menuBar.addMenu(menu);
} else {
Menu parent = getMenuById(menu.getParentId());
menuBar.addChildMenu(parent, menu);
}
}
现在我正在努力创建与此相同的 Java 8 代码,以下是我正在尝试的代码,
// The following code is not complete , just trying
menuList.stream().filter(menu -> isParentMenu(menu.getId()))
.map(menu -> menuBar.addMenu(menu))
最佳答案
老实说,我认为您的代码不需要更改。就现在的情况来看,已经很清楚了。将其更改为流甚至可能会增加一些开销,使其性能低于循环。
一个非常简单的流解决方案是:
MenuBar menuBar = new MenuBar();
menuList.stream().forEach(x -> {
if (isParentMenu(x.getId())) {
menuBar.addMenu(x);
} else {
Menu parent = getMenuById(x.getParentId());
menuBar.addChildMenu(parent, x);
}
});
或者,您可以使用partitioningBy
:
Map<Boolean, List<Menu>> map = menuList.stream().collect(Collectors.partitioningBy(x -> isParentMenu(x.getId())));
map.get(true).stream().forEach(menuBar::addMenu);
map.get(false).stream().forEach(x -> {
Menu parent = getMenuById(x.getParentId());
menuBar.addChildMenu(parent, x);
});
关于Java 8 : Iterate over a list and add to a map based on condition,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55663288/