Home > Software design >  How can I use the Java stream in order to create an array iterating in all the element of a nested c
How can I use the Java stream in order to create an array iterating in all the element of a nested c

Time:11-17

I am working on a Java application and I am trying to understand if Stream concept can be useful for my use case.

I am trying to do something similar to what I found into an example but my use case seems to be more complex. This was the original example:

String[] profili = utente.getRuoli()
                 .stream().map(a -> "ROLE_"   a).toArray(String[]::new);

Basically it is creating an array starting from a stream.

Following my situation. I have this main User DTO class representing an user:

@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;   
}

The previous DTO class contains this field representing a collection of user types (for example "ADMIN", "READER", "WRITER", etcetc). This because an user can have multiple types:

private Set<UserType> userTypes;

This is the UserType structure:

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

Also this class contains a field representing a collection of operations (this because a user type can have multiple operation that can perform on the system), this field:

Set<Operation> operations;

Now I am asking if I can use the stream in a similar way to the original example in order to create an array of all the operations contained into all the user types.

Is it possible? What could be a smart solution? Or maybe the best way is the "old style" (iterate on all the object into the userTypes Set, then iterate on all the element into the operations Set and manually add to an array?). It will work but what could be a neat and elegant solution using stream? (if exist)

CodePudding user response:

Use flatMap() on the operations Set, with distinct():

Operation[] operations = user.getUserTypes().stream()
  .map(UserType::getOperations)
  .flatMap(Set::stream)
  .distinct()
  .toArray(Operation[]::new);

CodePudding user response:

It sounds like what you want is just

userList.stream()
  .flatMap(user -> user.getUserTypes().stream())
  .flatMap(userType -> userType.getOperations().stream())
  .toArray(Operation[]::new);

...assuming you're using getters. This gives you every operation for every user type for every user.

  • Related