简体   繁体   中英

Using Streams and filter in Java and matching with a varargs

I know that .contains needs a string. Varargs can be a String structure of more than one. Like String... role can be "user", "admin" . Or String... role can be "user" .

Whatever is passed into it will be used.

So I have a filter - where I am trying to see if the getter thats a type String contains the value found in the varargs...

 String a = Arrays.toString(role);
 System.out.print(a);
 TypeOfObject roles = userProjectRoles.stream().filter(userProjectRole ->
    userProjectRole.getRole().getName().equals(a)).findFirst().orElse(null);

a has brackets and it is not a string, but an Array sent as a string value.

Can you help me on how to fix this?

Convert input array to Set and use its contains() method

 Set<String> roleSet = new HashSet<>(Arrays.asList(role));
 TypeOfObject roles = userProjectRoles.stream()
     .filter(userProjectRole -> roleSet.contains(userProjectRole.getRole().getName())
     .findFirst()
     .orElse(null);

You can use filter userProjectRoles with the anyMatch method to check if roles contains that role:

var result = userProjectRoles.stream()
  .map(role -> role.getRole().getName())
  .filter(roleName -> Arrays.stream(roles).anyMatch(role -> roleName.equals(role)))
  .collect(Collectors.toList())

or

var result = userProjectRoles.stream()
  .map(role -> role.getRole().getName())
  .filter(roleName -> {
    for (String role : roles) if (roleName.equals(role)) return true;
    return false;
  })
  .collect(Collectors.toList())

This will give you all of the elements in userProjectRoles whose names are also in the roles array, if I understand your question correctly.

If it's the other way around and you want all the elements in the roles array that are also in userProjectRoles , you can do this:

List<String> roleNames = 
  roles.stream()
    .map(role -> role.getRole().getName())
    .collect(Collectors.toList());
var result = Arrays.stream(roles).stream()
  .filter(roleNames::contains)
  .collect(Collectors.toList())

I presume you're trying to get rid of [ and ] from Arrays#toString but it's unclear since there is no direct answer. If so, this is how.

It is worth noting that this is unsafe because the result of role could be multiple values and not a single one.

String a = Arrays.toString(role).replaceAll("\\[", "").replaceAll("]", "");

An alternative might be to check if the array of roles contains the role name. Ie;

TypeOfObject roles = userProjectRoles.stream()
    .filter(userProjectRole -> Stream.of(a).anyMatch(roleName -> userProjectRole.getRole().getName().equals(roleName))
    .findFirst()
    .orElse(null);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM