英文:
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);
然而,这看起来过于冗长,而且主要需要:
- 对输出进行字符串的最终转换
- 对传递到筛选器中的每个对象进行类型转换
针对上述问题,我尝试了.map(String.class::cast)
:
- 在
lst.stream()
之后 - 在
filter(o -> ((String) o).contains("@"))
之后
但是这些尝试都没有奏效。
有什么提示吗?
英文:
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:
- a final cast to String of output
- a cast for each object passed into filter
For the above issued, I tried .map(String.class::cast)
- After
lst.stream()
- After
filter(o -> ((String) o).contains("@"))
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<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
</details>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论