[英]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.