Spring Boot 如何过滤Java流并只返回以提供的子字符串列表开头的项

bxgwgixi  于 2023-06-22  发布在  Spring
关注(0)|答案(1)|浏览(167)

我有一个当用户在Sping Boot 应用程序中进行身份验证时返回的权限列表。
例如,我获得了授权列表,如:

  1. user_1_authority,
  2. user_2_authority,
  3. group_1_authority,
  4. group_2_authority,
  5. test_1_authority,
  6. test_2_authority,
  7. driver_x_authority,
  8. ...

我想过滤这些权限,以便只返回以“user_”或“group_”开头的权限。
我想知道如何使用Java流来返回一个新的过滤权限列表,以获得如下内容:

  1. List<String> authoritiesStartingWithList = Arrays.asList("user_", "group_");
  2. public Collection<GrantedAuthorities> filterAuthorities(Authentication authentication, List<String> authoritiesStartingWithList) {
  3. return authentication.getAuthorities().stream().contains(authoritiesStartingWithList);
  4. }

这将返回一个仅包含以下内容的列表:

  1. user_1_authority,
  2. user_2_authority,
  3. group_1_authority,
  4. group_2_authority,
4nkexdtk

4nkexdtk1#

请尝试以下解决方案:

  1. List<String> authoritiesStartingWithList = Arrays.asList("user_", "group_");
  2. public Collection<GrantedAuthority> filterAuthorities(Authentication authentication, List<String> authoritiesStartingWithList) {
  3. return authentication.getAuthorities().stream().filter(this::startsWithOneOfPredefinedValues).collect(Collectors.toList());
  4. }
  5. private boolean startsWithOneOfPredefinedValues(GrantedAuthority grantedAuthority) {
  6. return authoritiesStartingWithList.stream().anyMatch(i->grantedAuthority.getAuthority().startsWith(i));
  7. }

过滤方法用于遍历前缀列表以检查是否存在任何匹配,如果没有找到匹配,则从流中过滤出权限。

相关问题