Revathi
Revathi

Reputation: 9

How to get output using stream in Java

Trying to reduce the performance and I want to modify this code using streams. Tried some ways but I couldn't get the exact result.

String[] arr = {"test", "test1", "test2"};
for (String a : arr){
   String id = a.trim();
   if (id.isEmpty()) {
       continue;
    }
    Message childMsg = (Message)msg.get(id);
     if (childMsg == null) {
       continue;
     }
     String prodId = childMsg.getProperty("ID");
     String expDate  = childMsg.getProperty("DATE");
     String prodMapKey = prodId + "_" + expDate;
     if(hasMap && formId != null){
     if(childMsg.getProperty("ID").equals(formId)){
        map.put(prodMapKey,childMsg);
      }
    } else {
     map.put(prodMapKey,childMsg);
   }
 }

Output should be, need to put the values in the map, but I couldn't do so.

List<String> players = Arrays.asList(arr);
players.stream()
       .filter(item-> !item.trim().isEmpty())
       .filter(item -> msg.get(item)!= null)
       .forEach(System.out::println);

Upvotes: 0

Views: 187

Answers (1)

Anonymous
Anonymous

Reputation: 86333

Map<String, Message> map = Arrays.stream(arr)
        .map(String::trim)
        .filter(id -> ! id.isEmpty())
        .map(msg::get)
        .filter(Objects::nonNull)
        .filter(childMsg -> ! (hasMap && formId != null)
                || childMsg.getProperty("ID").equals(formId))
        .collect(Collectors.toMap(childMsg -> childMsg.getProperty("ID") + "_" + childMsg.getProperty("DATE"),
                childMsg -> childMsg);

Code is not tested. And I do not expect it to perform any better than what you had.

Upvotes: 1

Related Questions