JAVA Stream API 使用

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

JAVA Stream API usage

问题

以下是翻译好的部分:

  1. 我有一个User实体类
  2. class User{
  3. private String id;
  4. private String email;
  5. private String name;
  6. private int age;
  7. ... 等等
  8. }
  9. 我想只检索User类的一些属性并创建一个映射列表
  10. 如何使用Java 8流来实现这个
  11. 换句话说我想要做到这一点
  12. ```java
  13. Stream<User> s = users.stream();
  14. // 仅从用户中检索电子邮件和姓名属性,并使用JAVA 8流创建映射

返回类型应该是List<Map<String, String>>,并且如下所示

{
{
"name" : "a",
"email" : "aa@aa.com"
},
{
"name" : "b",
"email" : "bb@bb.com"
}
}

  1. 希望这对你有所帮助!
  2. <details>
  3. <summary>英文:</summary>
  4. I have a User entity
  5. class User{
  6. private String id;
  7. private String email;
  8. private String name;
  9. private int age :
  10. ... etc
  11. }
  12. I want to only retrieve some attributes of the User class and make a list of map.
  13. How can I do this using Java 8 stream?
  14. In other words I want to do this

Stream <User> s = List <User> users.stream();
// only retrive email and name attribute from user and make a map using JAVA 8 Stream

  1. return type should be `List &lt;Map &lt;String, String&gt;&gt;` and look like below
  2. {
  3. {
  4. &quot;name&quot; : &quot;a&quot;,
  5. &quot;email&quot; : &quot;aa@aa.com&quot;
  6. },
  7. {
  8. &quot;name&quot; : &quot;b&quot;,
  9. &quot;email &quot; : &quot;bb@bb.com&quot;
  10. }
  11. }
  12. </details>
  13. # 答案1
  14. **得分**: 2
  15. 你可以像这样使用 `Stream.map()`
  16. ```java
  17. List<Map<String, String>> result = users.stream().map(user -> {
  18. Map<String, String> map = new HashMap<>();
  19. map.put("name", user.getName());
  20. map.put("email", user.getEmail());
  21. return map;
  22. }).collect(Collectors.toList());

Stream.map() 可以用于将你的流对象映射到任何你想要的内容。

英文:

You can use Stream.map() like this:

  1. List&lt;Map&lt;String,String&gt;&gt; result=users.stream().map(user-&gt;{
  2. Map&lt;String,String&gt; map=new HashMap&lt;&gt;();
  3. map.put(&quot;name&quot;,user.getName());
  4. map.put(&quot;email&quot;,user.getEmail());
  5. return map;
  6. }).collect(Collectors.toList());

Stream.map() can be used to map your stream object to anything you want.

huangapple
  • 本文由 发表于 2020年8月11日 15:33:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/63353524.html
匿名

发表评论

匿名网友

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

确定