Refactor double foreach and if statment into java 8 solution

java 8 foreach multiple statements
java 8 foreach list of objects
foreach inside foreach java 8
java 8 for loop range
refactoring if statements
replace multiple if statements in java
nested for loop in java 8
foreach() method in java 8

Well like you can notice I try to get users on a specific project (and my code works)

List<User> allUsers = userRepository.findAll();
List<UserDto> usersInSpecificProject = new ArrayList<>();

for(User user: allUsers){
    Set<Project> allProjects = user.getProjects();
    for(Project project: allProjects){
    if(project.getId().equals(projectId)){
            usersInSpecificProject.add(user);
        }
    }
}

If it would've been single for + if I could easily do something like:

allUsers.stream()
    .filter(u -> u.someCondition)
    .collect(Collectors.toList());

But what if I need to loop in a loop?

You could do this:

List<User> usersInSpecificProject =
  allUsers.stream()
        .filter(u -> u.getProjects().stream()
                                    .map(Project::getId)
                                    .anyMatch(pid -> pid.equals(projectId)))
        .collect(Collectors.toList());

Your original version should be improved by break after condition if(project.getId().equals(projectId)) is satisfied.

That's why the filter using anyMatch() to break on first match.

For more elegant version, you could factor our the filter:

Predicate<User> hasProject = u -> u.getProjects().stream()
                                   .map(Project::getId)
                                   .anyMatch(pid -> pid.equals(projectId));
List<User> result = allUsers.stream().filter(hasProject).collect(toList());

Java 8 forEach() Loop Example, Java 8 has introduced a new way to loop over a List or Collection, by using the It will throw IllegalStateException if you try to call another method on this Stream. For example, in our next two examples, we cannot replace lambda statement to iterate over every element of a list, set or stream in Java. Home » Java » Refactor double foreach and if statment into java 8 solution. Refactor double foreach and if statment into java 8 solution . 2020 Java Leave a

You can do it like so,

List<User> users = allUsers.stream()
        .filter(u -> u.getProjects().stream().anyMatch(p -> p.getId().equals(projectId)))
        .collect(Collectors.toList());

For each user, you need to have a filter predicate to check whether the user has a project with the given projectId value. If so, we merely collect the satisfying User objects into a result container.

In case if you need to transform User domain objects into UserDto type as mentioned in your problem statement, you need to have an additional map function for the conversion like this.

List<UserDto> users = allUsers.stream()
        .filter(u -> u.getProjects().stream().anyMatch(p -> p.getId().equals(projectId)))
        .map(u -> new UserDto(u.getProjects()))
        .collect(Collectors.toList());

However you may have to change that according to your UserDto class.

Code Smells: If Statements, This guide will help refactor poorly implemented Java if statements to make your In the last two articles, we've been looking at the smells from a single method, validateQuery . Step 8: Simplify the Logic Possible solutions: zip ---> forEach , the method calls are written in different order where zip() call  In Java 8, it is already assumed that you will be iterating over a list, so it’s made easy for you to do via the stream() method. The statement is the new Java 8 way of iterating over a Collection and providing the objects for processing: campaigns.stream()

You can use Java 8's stream() function like this to achieve it:

usersInSpecificProject.addAll(allUsers.stream()
        .filter(u -> u.getProjects().stream().map(Project::getId)
        .anyMatch(projId-> projId.equals(projectId)))
        .collect(Collectors.toList()));

Here is the link to the documentation on how stream() works.

Code Smells: Deeply Nested Code, Solution 1: Java 8 to the rescue I've shown in previous blogs and talks that nested for/if statements can often be replaced with Java 8 Streams  Above we implemented the if/else logic using the Stream filter () method to separate the Integer List into two Streams, one for even integers and another for odd integers. In this quick article, we’ve explored how to create a Java 8 Stream and how to implement if/else logic using the forEach () method. Furthermore, we learned how to use the

3 Reasons why You Shouldn't Replace Your for-loops by Stream , Wait a minute Java 8 has been out for over a year now, and the thrill has gone The result of the following two pieces of logic is the same care, i.e. only if you truly benefit from the internal, functional iteration (e.g. when forEach() compared to an ordinary for loop is so significant in general that using it by  Yesterday I found some nice video from some IT conference about removing if statements from code. I saw a very nice example of refactoring. I am curious what do you think about it, especially what weak points do you see in such approach. 1) We have a class with very "nice" method:

Refactoring for loop (clean code aspect), Probably you could first split your array based on some condition, thus you have two arrays. Then you iterate each of them and no if needed,  In this demo, Trisha highlights the benefits of using Java 8, demonstrates how to automatically refactor your code to make use of them, and compare performance and readability of the code before

Refactoring Deeply Nested Code, Tease out the logic of snarled, deeply nested if/else constructs with the Flatten Conditionals refactoring. It's tempting to think that automated refactoring tools offer a solution to this problem. Tools for Java and C# are quite advanced. to the top level is rather straightforward, the nested if statement can  Refactoring to Java 8. Why Java 8? 8 9 s/ms for vs forEach (1000 elements) Should you migrate your code to Java 8? It Depends.

Comments
  • You can add a method in User called hasProject(ProjectId projectId), this can be your condition. Why do you want 2 for loops?
  • Well, I want to get all users from the specific project. That's why I need to loop through all Users. Check their Projects. and then check if their projects have id with the specific ID. Is there an easier way to achive that?
  • You seem to be using a database - it would be more efficient and simpler to write the ad hoc query.
  • You have a Set of Projects in User. You can use the for loop in there to check if the User has the project -> create method in User hasProject which can be called in the filter. But iso using for loop you can also change Set<Project> to HashMap<ProjectId,Project> . Then inside your method you can return map.contains(projectId).
  • If you're trying to optimize this, you shouldn't use userRepository.findAll() there to begin with. Use actual database operation, like findByProject or something.
  • Or anyMatch(projectId::equals)
  • That won't work: after flatMap, this is a Stream<Project>, not Stream<User>.