Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 How to filter not different entity from two collections?

I want to use Java 8 stream filter collections but i found all example is one collections , Java 6 is :

public class User {
public Long id;
public String name;

public User(Long id, String name) {
    this.id = id;
    this.name = name;
}

   List<User> usersA = new ArrayList<>();

    usersA.add(new User(1l,"A"));
    usersA.add(new User(2l,"B"));
    usersA.add(new User(3l,"C"));

    List<User> usersB = new ArrayList<>();
    usersB.add(new User(33l,"A"));
    usersB.add(new User(34l,"B"));
    usersB.add(new User(35l,"D"));
    usersB.add(new User(36l,"C"));

    List<User> tempUser = new ArrayList<>();
    tempUser.addAll(usersB);

    for (User user : usersA) {
        for (User user1 : tempUser) {
            System.out.println(user1.getName().equalsIgnoreCase(user.getName()));
            if (user1.getName().equalsIgnoreCase(user.getName())){
                System.out.println("remove:"+user1.getName());
                tempUser.remove(user1);
                break;
            }
        }

    }

    System.out.println("last:"+tempUser);

And Java 8 I want to use stream api not use foreach ,can u take a example for me ? thanks

like image 882
user2930390 Avatar asked Dec 17 '25 20:12

user2930390


1 Answers

So, if I understand correctly, you want to create a new list containing all the users of usersB, except those that have the same name as any of the users in usersA, right?

First of all, I would change the strategy: instead of adding all the users, then removing some, I would only add the users that belong to the list in the first place.

And in Java 8, that can be done with

List<User> result = 
    usersB.stream()
          .filter(u -> !userNameIn(u, usersA))
          .collect(Collectors.toList());

with userNameIn defined as

private boolean userNameIn(User u, List<User> users) {
    return users.stream().anyMatch(user -> user.getName().equalsIgnoreCase(u.getName()));
}

That won't be very efficient if usersA contains a large number of users. A more efficient solution would be to store all the lowercase names of usersA in a HashSet, and replace the method with

List<User> result = 
    usersB.stream()
          .filter(u -> !lowercaseNames.contains(u.getName().toLowerCase()))
          .collect(Collectors.toList());
like image 195
JB Nizet Avatar answered Dec 20 '25 08:12

JB Nizet



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!