JAVA Stream API 使用

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

JAVA Stream API usage

问题

以下是翻译好的部分:

我有一个User实体类

class User{
private String id;
private String email;
private String name;
private int age;
... 等等
}

我想只检索User类的一些属性并创建一个映射列表

如何使用Java 8流来实现这个

换句话说我想要做到这一点

```java
Stream<User> s = users.stream();
// 仅从用户中检索电子邮件和姓名属性,并使用JAVA 8流创建映射

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

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


希望这对你有所帮助!

<details>
<summary>英文:</summary>

I have a User entity

    class User{
    private String id; 
    private String email;
    private String name;
    private int age :
    ... etc
    }

I want to only retrieve some attributes of the User class and make a list of map.

How can I do this using Java 8 stream?

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


return type should be `List &lt;Map &lt;String, String&gt;&gt;` and look like below

    {
     {
       &quot;name&quot; : &quot;a&quot;,
       &quot;email&quot; : &quot;aa@aa.com&quot;
    },
    {
       &quot;name&quot; : &quot;b&quot;,
       &quot;email &quot; : &quot;bb@bb.com&quot;
    
    }
    }




</details>


# 答案1
**得分**: 2

你可以像这样使用 `Stream.map()`:

```java
List<Map<String, String>> result = users.stream().map(user -> {
    Map<String, String> map = new HashMap<>();
    map.put("name", user.getName());
    map.put("email", user.getEmail());
    return map;
}).collect(Collectors.toList());

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

英文:

You can use Stream.map() like this:

List&lt;Map&lt;String,String&gt;&gt; result=users.stream().map(user-&gt;{
            Map&lt;String,String&gt; map=new HashMap&lt;&gt;();
            map.put(&quot;name&quot;,user.getName());
            map.put(&quot;email&quot;,user.getEmail());
            return map;
        }).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:

确定