0

I am using Java application.

Here is my map

{
    "name": "John",
    "address": "US"
}

Code block:

Map<String, Object> response = new HashMap<>();

final List<String> TYPES = List.of("name", "gender", "age");

String display = "text"; // text, password

for (Map.Entry<String, Object> entry : map.entrySet()) {
    if (TYPES.contains(entry.getKey())) {
        String result = (String) entry.getValue();

        if (display.equals("text"))) {
           result = // do some manipulation
        } else if (display.equals("password")) {
            result = // do some manipulation
        }

        response.put(entry.getKey(), result);
    } else {
        response.put(entry.getKey(), entry.getValue());
    }
}

Based on the display type, I get different responses. Above code is working fine. Is it more efficient way to do this code using Java Streams?

Galet
  • 5,853
  • 21
  • 82
  • 148
  • What does `String display = text; // text, password` even mean? Is `text` a variable or is this a typo where you forgot to put `text` into quotes? – daniu Feb 25 '21 at 09:59
  • @daniu text is a enclosed string. – Galet Feb 25 '21 at 10:01
  • So then you don't need to query the `display.equals(...)` below, do you? – daniu Feb 25 '21 at 10:06
  • @daniu I need equals condition to change the value of the result – Galet Feb 25 '21 at 10:53
  • But in your code, `display.equals("text")` will always be executed, and `display.equals("password")` never. So either you pass in the `display` value, or you can get rid of that if/else. – daniu Feb 25 '21 at 13:06
  • @daniu Oh I missed the if condition. Update now – Galet Feb 25 '21 at 13:12
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/229203/discussion-between-galet-and-daniu). – Galet Feb 25 '21 at 13:45

1 Answers1

0

Try this:

map.entrySet().stream()
              .filter(x ->TYPES.contains(x.getKey())
              .collect(Collectors.toMap(x -> x.getKey(), p -> (x.getValue().equals("text") || x.getValue().equals("display"))? "some_manipolation" : x.getValue())) 
gcryptolo
  • 1
  • 1