将对象转换为List<String>

huangapple go评论89阅读模式
英文:

Casting an Object to List<String>

问题

我有一个包含元素值为List<String>Map<String, Object>

现在我需要筛选后者并检索第一个包含@的值。

我做过的最好的尝试是:

  1. Map<String, Object> map = new HashMap<>();
  2. map.put("alias", List.of("Mxxx", "fstarred@mymail.org"));
  3. final Object obj = map.get("alias");
  4. final List lst = (List) obj;
  5. final Object output = lst.stream()
  6. .filter(o -> ((String) o).contains("@"))
  7. .findFirst()
  8. .orElse(null);

然而,这看起来过于冗长,而且主要需要:

  1. 对输出进行字符串的最终转换
  2. 对传递到筛选器中的每个对象进行类型转换

针对上述问题,我尝试了.map(String.class::cast)

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

但是这些尝试都没有奏效。

有什么提示吗?

英文:

I have a Map&lt;String,Object&gt; which contains an element value of List&lt;String&gt;

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

The best I did was:

  1. Map&lt;String, Object&gt; map = new HashMap&lt;&gt;();
  2. map.put(&quot;alias&quot;, List.of(&quot;Mxxx&quot;, &quot;fstarred@mymail.org&quot;));
  3. final Object obj = map.get(&quot;alias&quot;);
  4. final List lst = (List) obj;
  5. final Object output= lst.stream()
  6. .filter(o -&gt; ((String) o).contains(&quot;@&quot;))
  7. .findFirst()
  8. .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 -&gt; ((String) o).contains(&quot;@&quot;))

None of these approaches did work.

Any hints?

答案1

得分: 5

按照建议,不要使用原始类型。以下是你应该使用的方法。

  1. Map<String, List<String>> map = new HashMap<>();
  2. map.put("alias", List.of("Mxxx", "fstarred@mymail.org"));
  3. List<String> list = map.get("alias");
  4. String output = list.stream()
  5. .filter(o -> o.contains("@"))
  6. .findFirst()
  7. .orElse(null);
  8. System.out.println(output);

输出

  1. fstarred@mymail.org
英文:

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

  1. Map&lt;String, List&lt;String&gt;&gt; map = new HashMap&lt;&gt;();
  2. map.put(&quot;alias&quot;, List.of(&quot;Mxxx&quot;, &quot;fstarred@mymail.org&quot;));
  3. List&lt;String&gt; list = map.get(&quot;alias&quot;);
  4. String output= list.stream()
  5. .filter(o -&gt;o.contains(&quot;@&quot;))
  6. .findFirst()
  7. .orElse(null);
  8. System.out.println(output);

Prints

  1. fstarred@mymail.org
  2. </details>

huangapple
  • 本文由 发表于 2020年9月2日 20:30:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/63705580.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定