How can I convert this source code to lambda?

jay :

It consists of a map in the list object. I try to match lists with the same id by comparing them through loop statements. How can I convert to lambda?

List<Map<String, String>> combineList = new ArrayList<>(); // Temp List
for(Map titleMap : titleList) { // Name List
   for(Map codeMap : codeList) { // Age List
      if(titleMap.get("ID").equals(codeMap.get("ID"))) { // compare Id
         Map<String,String> tempMap = new HashMap<>();
          tempMap.put("ID", titleMap.get("ID"));
          tempMap.put("NAME", titleMap.get("NAME"));
          tempMap.put("AGE", codeMap.get("AGE"));
          combineList.add(tempMap);
      }
   }
}
Vinay Prajapati :

You are already doing it in efficient manner. So if you want you could change same code to just use stream().forEach or if want to use streams more do it as below:

titleList.stream()
        .forEach(titleMap ->
            combineList.addAll(
                codeList.stream()
                    .filter(codeMap -> titleMap.get("ID").equals(codeMap.get("ID")))
                    .map(codeMap -> {
                      Map<String, Object> tempMap = new HashMap<>();
                      tempMap.put("ID", titleMap.get("ID"));
                      tempMap.put("NAME", titleMap.get("NAME"));
                      tempMap.put("ID", codeMap.get("ID"));
                      tempMap.put("AGE", codeMap.get("AGE"));
                      return tempMap;
                    })
                    .collect(Collectors.toList())
            )
        );

Notice that you have to filter from the codeList each time because your condition is that way. Try using a class in place of Map to be more efficient, cleaner and effective.

Guess you like

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