pitsa
pitsa

Reputation: 93

How to use Collectors toMap() to return single value?

I am trying to get Collectors toMap() working to return single value from set of headers. For example: input string

[clients:MYSQL,EDW,Oracle,WSO2,SMTP, UniqueName:Domain_v1]

code:

private static Map<String, Object> headersTomap(String headers) {
      String sHeaders = headers.replace("[", ""); sHeaders = sHeaders.replace("]",
      ""); logger.debug("sHeaders: " + sHeaders); return
      Arrays.stream(sHeaders.split(", ")).map(s -> s.split(":"))
      .collect(Collectors.toMap(s -> s[0], s -> s[1]));

      }

Above code returns:

clients: MYSQL,EDW,Oracle,WSO2,SMTP
UniqueName: Domain_v1

Expected output is: Domain_v1

Please advise. The above code should return Domain_v1 as output for above input. Please help. Thank you.

Upvotes: 2

Views: 523

Answers (1)

Ryuzaki L
Ryuzaki L

Reputation: 40078

Since you have already converted string to Map, you can get the value for UniqueName key by using getOrDefault

Returns the value to which the specified key is mapped, or defaultValue if this map contains no mapping for the key.

Map<String,String> map = Arrays.stream(sHeaders.split(", ")).map(s -> s.split(":"))
  .collect(Collectors.toMap(s -> s[0], s -> s[1]));

 map.getOrDefault("UniqueName","Not Present");

Or in one sequence

Arrays.stream(sHeaders.split(", ")).map(s -> s.split(":"))
  .collect(Collectors.toMap(s -> s[0], s -> s[1]))
  .getOrDefault("UniqueName","Not Present");

If you just need value associated to UniqueName without Map then you can simply go for this approach

String res = Arrays.stream(sHeaders.split(", "))
                       .filter(s->s.contains("UniqueName:"))
                       .findFirst()
                       .map(name->name.split(":")[1])
                       .orElse("Not Present");

Upvotes: 1

Related Questions