-2

I have a Map<String,Object> which contains an element value of List<String>

Now I need to filter the latter and retrieve first value that contains @.

The best I did was:

    Map<String, Object> map = new HashMap<>();
    map.put("alias", List.of("Mxxx", "fstarred@mymail.org"));

    final Object obj = map.get("alias");
    final List lst = (List) obj;
    final Object output= lst.stream()
            .filter(o -> ((String) o).contains("@"))
            .findFirst()
            .orElse(null);

however looks to much verbose and mostly requires:

  1. a final cast to String of output
  2. a cast for each object passed into filter

For the above issued, I tried .map(String.class::cast)

  1. After lst.stream()
  2. After filter(o -> ((String) o).contains("@"))

None of these approaches did work.

Any hints?

Mario Codes
  • 689
  • 8
  • 15
Fabrizio Stellato
  • 1,727
  • 21
  • 52
  • 6
    [Never use raw types](https://stackoverflow.com/questions/2770321/what-is-a-raw-type-and-why-shouldnt-we-use-it) like `List`, as it messes everything up. Cast to `List` (which won't actually verify anything, it's an unchecked cast, but it will make your life easier). – Joachim Sauer Sep 02 '20 at 12:33
  • Is there a reason you're not using `Map>`? – Kayaman Sep 02 '20 at 12:45

1 Answers1

5

As suggested, don't use raw types. Here is the approach you should use.

Map<String, List<String>> map = new HashMap<>();
map.put("alias", List.of("Mxxx", "fstarred@mymail.org"));

List<String> list = map.get("alias");

String output= list.stream()
         .filter(o ->o.contains("@"))
         .findFirst()
         .orElse(null);

System.out.println(output);

Prints

fstarred@mymail.org
WJS
  • 36,363
  • 4
  • 24
  • 39