简体   繁体   English

How can I use Java Stream in order to iterate on a collection on object and use a specific string field of each object to create a new array?

[英]How can I use Java Stream in order to iterate on a collection on object and use a specific string field of each object to create a new array?

I am not so into Java Stream and I have the following problem.我不太喜欢 Java Stream 并且我有以下问题。

I am generating a JWT token in this way.我正在以这种方式生成 JWT 令牌。 The JWT token generation it is only the context on which I am working on but it is not strictly related to my problem. JWT 令牌生成只是我正在处理的上下文,但它与我的问题并不严格相关。 My problem is related about how to create a list of Strings from a specific field of n objects into a Set.我的问题与如何从 n 个对象的特定字段创建一个字符串列表到一个集合有关。

So I have the following situation:所以我有以下情况:

I have this User object:我有这个用户object:

@Data
public class User {
    
    private int id;
    private String firstName;
    private String middleName;
    private String surname;
    private char sex;
    private Date birthdate;
    private String taxCode;
    private String eMail;
    private String pswd;
    private String contactNumber;
    private Date createdAt;
    private Set<Address> addressesList;
    private Set<UserType> userTypes;

}

As you can see it contains the Set<UserType> userTypes field, representing a collection of possible user types (basically the user profiles such as "ADMIN", "READER", MODERATOR", this because in my system a single user can have multiple user types).如您所见,它包含Set<UserType> userTypes字段,表示可能的用户类型的集合(基本上是用户配置文件,例如“ADMIN”、“READER”、MODERATOR”,这是因为在我的系统中,单个用户可以拥有多个用户类型)。

And this is the UserType definition:这是UserType定义:

@Data
public class UserType {
    private int id;
    private String typeName;
    private String description;
    Set<Operation> operations;
}

So basically the interested field is the typeName .所以基本上感兴趣的领域是typeName Starting from a Set<UserType> userTypes I have to obtain a List of String, something like: **["ADMIN", "READER", "SIMPLE_USER"] where the array object is the value of the typeName field.Set<UserType> userTypes我必须获得一个字符串列表,例如:**["ADMIN", "READER", "SIMPLE_USER"] 其中数组 object 是typeName字段的值。

Into my code I have this method:在我的代码中,我有这个方法:

private String doGenerateToken(Map<String, Object> claims, UserDetailsWrapper userDetailsWrapper) {
    final Date createdDate = clock.now();
    final Date expirationDate = calculateExpirationDate(createdDate);
    
    // MOCKED USER PROFILES COLLECTION:
    ArrayList<String> userProfiles = new ArrayList<String>();
    userProfiles.add("SIMPLE_USER");
    userProfiles.add("MODERATOR");
    

    return Jwts.builder()
            .setClaims(claims)
            .setSubject(userDetailsWrapper.getUserDetails().getUsername())
            .claim("name", userDetailsWrapper.getUserCompleteInfo().getFirstName() + " " 
                         + userDetailsWrapper.getUserCompleteInfo().getMiddleName() + " "
                         + userDetailsWrapper.getUserCompleteInfo().getSurname())
            .claim("user_profiles", userProfiles)
            //.claim("user_profiles", userDetailsWrapper.getUserCompleteInfo().getUserTypes().stream().map(UserType::getUserType).collect(Collectors.toList()))
            .claim("authorities", userDetailsWrapper.getUserDetails().getAuthorities().stream().map(GrantedAuthority::getAuthority).collect(Collectors.toList()))
            .setIssuedAt(createdDate)
            .setExpiration(expirationDate)
            .signWith(SignatureAlgorithm.HS512, jwtConfig.getSecret().getBytes())
            .compact();
}

As you can see in the previous code snippet I have mocked the userProfiles ArrayList, then I am adding it to my JWT token payload by:正如您在前面的代码片段中看到的那样,我已经模拟了userProfiles ArrayList,然后我通过以下方式将其添加到我的 JWT 令牌有效负载中:

.claim("user_profiles", userProfiles)

It works fine.它工作正常。 The problem is that I have to do the same thing starting from the collection returned by (this is the previous mentioned Set<UserType> userTypes field):问题是我必须从返回的集合开始做同样的事情(这是前面提到的Set<UserType> userTypes字段):

userDetailsWrapper.getUserCompleteInfo().getUserTypes()

Basically I need a way to use Java Stream to iterate on this collection and then add the typeName field (that is a String) of each object into the array used by the claim() method as input parameter.基本上我需要一种方法来使用 Java Stream 来迭代这个集合,然后将每个 object 的typeName字段(即一个字符串添加到数组中作为输入方法使用的参数。

In the previous code you can find (commented out) an attempt that I have done but Eclipse give me error so it is wrong.在前面的代码中,您可以找到(注释掉)我所做的尝试,但 Eclipse 给我错误,所以这是错误的。

How can I try to implement this behavior using Java Stream?如何尝试使用 Java Stream 来实现此行为?

.claim("user_profiles",userDetailsWrapper.getUserCompleteInfo()
.getUserTypes().stream()
.map(UserType::getTypeName)
.collect(Collectors.toList()))

You should call map function to get typeName from UserType object.您应该调用 map function 从 UserType object 获取 typeName。 Try above code please请尝试上面的代码

You are trying to convert to the wrong type您正在尝试转换为错误的类型

.claim("user_profiles", userDetailsWrapper.getUserCompleteInfo()
    .getUserTypes()
    .stream()
    // Convert each UserType to a String using the getter for typeName field
    .map(UserType::getTypeName) 
    // Create a list from the Stream of TypeName strings
    .collect(Collectors.toList()))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何使用 Java Stream 修复此嵌套集合代码,以便从 object 的属性创建字符串数组? - How can I fix this nested collection code using Java Stream in order to create an array of string from the property of an object? 如何使用 Java 流来创建在嵌套集合的所有元素中迭代的数组? - How can I use the Java stream in order to create an array iterating in all the element of a nested collection? 如何使用 Java stream 收集来创建 map,而不是 ZA8CFFDE6331BD59EB666AC9C - How do I use Java stream collect to create a map with a String as the key instead of object? How to use Java Stream API to iterate through a HashMap with custom object - How to use Java Stream API to iterate through a HashMap with custom object 如何使用循环创建新对象? - How can I use a loop to create a new object? 如何在 JAVA 中使用字符串变量作为对象名称? - How can i use string variable as an object name in JAVA? 无法在 Java 中的 Object 数组上使用 Stream 方法 - Not able to use Stream method on Array of Object in Java 每次我使用String时,它是否会创建一个新的String对象? - Every time I use String, does it create a new String object? 地图的值是一个对象。 如何使用/迭代所有这些变量? (Java) - Map's value is an object. How can I use/iterate through all those variables? (Java) 如何在反应式Java中将新对象添加到现有流中? - How can I add in reactive Java a new Object to an existing stream?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM