Adding a Map into list. The map is created when looping a list

Anonymous :

I have getSemiFileInfos() in a list and I wanted to use stream and then loop each of element inside. Each element can still use getItem() or getItem2(). I will first create a map for item and item2 in itemMap, then I will store each loop of getSemiFileInfos() as a map into items list.

What I want is to have it in a single line. I am wondering whether is still possible.

private List<Map<String, String>> items;

items = new ArrayList<Map<String, String>>();

Map<String, String> itemMap = new HashMap<String, String>();
file.getFileInfo().getSemiFileInfos().stream().forEach(m-> 
    itemMap.put("item", m.getItem()); 
    itemMap.put("item2", m.getItem2().split(":",1))
);
items.add(mrphMap);
Eran :

You can map each element of your Stream into a Map with map() and then collect into a List:

List<Map<String, String>> items =
    file.getFileInfo()
        .getSemiFileInfos()
        .stream() 
        .map(m-> {
            Map<String, String> itemMap = new HashMap<String, String>();
            itemMap.put("item", m.getItem()); 
            itemMap.put("item2", m.getItem2().split(":",1)); // this doesn't produce a String
                                                             // value so perhaps you are
                                                             // missing some additional logic
                                                             // that would  extract one 
                                                             // String from the String[]
            return itemMap;
        })
        .collect(Collectors.toList());

Guess you like

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