Java 8: Iterate over a list and add to a map based on condition

Arpan Das :

I have a List, which I'm iterating over, and on some condition of each element, I am adding each element of the List to a data structure in a specific position, Following is the code in Java 7.

The data structure where I am adding each element from the list is,

/* The data structure has two slots, one for parents and another for children */
MenuBar menuBar = new MenuBar();

Now the code snippet is,

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);
    }
}

Now I am struggling to create a Java 8 code equivalent to the same, Following is what I am trying on,

// The following code is not complete , just trying
   menuList.stream().filter(menu -> isParentMenu(menu.getId()))
   .map(menu -> menuBar.addMenu(menu))
Sweeper :

I don't think your code needs to be changed , to be honest. As it is now, it is clear enough. Changing it to streams might even add some overheads, making it less performant than a loop.

A really simple streams solution would be:

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);
    }
});

Alternatively, you can use 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);
});

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=135033&siteId=1