比较java中的两个数组列表

时间:2016-04-27 14:49:51

标签: java arrays loops

我有两个不同的数组oldUsers和newUsers包含User类的实例。用户包含firstname,lastname和age属性。我想知道newUsers数组中具有相同属性的oldUsers对象的数量。我应该使用两个for循环并比较每个阵列一个或者是否有一个可以完成相同工作的函数?

3 个答案:

答案 0 :(得分:2)

假设您的User个对象正确实现了equals()hashCode(),我会使用其中一个列表' retainAll(Collection other)方法来制作两个列表的交集,然后返回其大小。

答案 1 :(得分:2)

首先需要覆盖equals()hashCode()。然后,您可以实现intersection()方法。

Number of identical values: 2
------------------------------
- { 'firstname': 'Bob', 'lastname': 'Smith', 'age': 30 }
- { 'firstname': 'Robert', 'lastname': 'Brown', 'age': 51 }

主要

import java.util.*;

public class Main {
    public static void main(String[] args) {
        List<User> oldUsers = new ArrayList<User>();
        List<User> newUsers = new ArrayList<User>();
        List<User> intersect;

        oldUsers.addAll(Arrays.asList(
            new User("Bob", "Smith", 30),
            new User("Tom", "Jones", 42),
            new User("Robert", "Brown", 51),
            new User("James", "Jones", 28)
        ));

        newUsers.addAll(Arrays.asList(
            new User("Robert", "Brown", 51), // Same
            new User("Bob", "Smith", 30),    // Same
            new User("Tom", "Jones", 21),
            new User("James", "Hendrix", 28)
        ));

        intersect = intersection(oldUsers, newUsers);

        System.out.printf("Number of identical values: %d%n%s%n",
                intersect.size(), "------------------------------");
        for (User user : intersect) {
            System.out.printf("- %s%n", user);
        }
    }

    // http://stackoverflow.com/a/5283123/1762224
    public static <T> List<T> intersection(List<T> list1, List<T> list2) {
        List<T> list = new ArrayList<T>();
        for (T t : list1) {
            if (list2.contains(t)) {
                list.add(t);
            }
        }
        return list;
    }
}

用户

public class User {
    private String firstname;
    private String lastname;
    private int age;

    public String getFirstname() { return firstname; }
    public void setFirstname(String firstname) { this.firstname = firstname; }

    public String getLastname() { return lastname; }
    public void setLastname(String lastname) { this.lastname = lastname; }

    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }

    public User(String firstname, String lastname, int age) {
        super();
        this.firstname = firstname;
        this.lastname = lastname;
        this.age = age;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + age;
        result = prime * result + ((firstname == null) ? 0 : firstname.hashCode());
        result = prime * result + ((lastname == null) ? 0 : lastname.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (obj == null) return false;
        if (getClass() != obj.getClass()) return false;

        User other = (User) obj;

        if (age != other.age) return false;

        if (firstname == null) {
            if (other.firstname != null) return false;
        } else if (!firstname.equals(other.firstname)) return false;

        if (lastname == null) {
            if (other.lastname != null) return false;
        } else if (!lastname.equals(other.lastname)) return false;

        return true;
    }

    @Override
    public String toString() {
        return String.format("{ 'firstname': '%s', 'lastname': '%s', 'age': %d }",
                firstname, lastname, age);
    }
}

替代方法

设置::全部保留

public static <T> List<T> intersection(List<T> list1, List<T> list2) {
    Set<T> set = new HashSet<T>(list1);
    set.retainAll(new HashSet<T>(list2));
    return new ArrayList<T>(set);
}

List :: Java 8 Filter Stream

public static <T> List<T> intersection(Collection<T> list1, Collection<T> list2) {
    return list1.stream().filter(item -> list2.contains(item)).collect(Collectors.toList()); 
}

答案 2 :(得分:0)

如果您已正确实施equals()hashCode(),则可以将oldUsers数组中的所有输入置于Set,然后检查来自newUsers的数据是Set或不是O(max(n, m))。这将在Set中有效(O(n)中的数据位于newUsers,如果它们位于O(m),请检查O(n) + O(m) = O(max(n,m)),因此您n },其中oldUsers的大小为m列表,newUsers的大小为 private int numberOfSameUsers(ArrayList<User> oldUsers, ArrayList<User> newUsers) { Set<User> oldUsersSet = new HashSet<>(oldUsers); int counter = 0; for (int i = 0; i < newUsers.size(); i++) if (oldUsersSet.contains(newUsers.get(i))) counter++; return counter; } 列表。)

例如:

{{1}}