将对象转换为List<String>

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

Casting an Object to List<String>

问题

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

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

我做过的最好的尝试是:

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);

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

  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:

    Map&lt;String, Object&gt; map = new HashMap&lt;&gt;();
    map.put(&quot;alias&quot;, List.of(&quot;Mxxx&quot;, &quot;fstarred@mymail.org&quot;));

    final Object obj = map.get(&quot;alias&quot;);
    final List lst = (List) obj;
    final Object output= lst.stream()
            .filter(o -&gt; ((String) o).contains(&quot;@&quot;))
            .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 -&gt; ((String) o).contains(&quot;@&quot;))

None of these approaches did work.

Any hints?

答案1

得分: 5

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

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);

输出

fstarred@mymail.org
英文:

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

Map&lt;String, List&lt;String&gt;&gt; map = new HashMap&lt;&gt;();
map.put(&quot;alias&quot;, List.of(&quot;Mxxx&quot;, &quot;fstarred@mymail.org&quot;));

List&lt;String&gt; list = map.get(&quot;alias&quot;);

String output= list.stream()
         .filter(o -&gt;o.contains(&quot;@&quot;))
         .findFirst()
         .orElse(null);

System.out.println(output);

Prints

fstarred@mymail.org


</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:

确定