迭代并组合不同对象的两个排序的arraylists

时间:2015-02-04 13:57:58

标签: java android sorting arraylist

我的情况是这样的:我有两个具有不同类型对象的arraylists。每个对象都有一个字段名称和一个字段日期 ArrayList事件,ArrayList事物。我按名称对arraylists进行了排序,如果名称相同,则按日期排序。

假设 ArrayList1 具有以下对象: event1 01.12,event1 05.12,event2 04.03,event3 05.05

ArrayList2 包含: event0 02.01,event2 05.10

现在我想制作一个包含带有事件名称的textview的TableRow和带有日期的另一个textview。 所以我的表布局将是这样的:

Event0    02.11(from2)
Event1    01.12(from1), 05.12(from1)
Event2    02.01(from2), 04.03(from1)
Event3    05.10(from1)

如何迭代2个arraylists并获取每个独特事件及其在TableRow中显示的所有日期?

我按照这个排序

Collections.sort(alist, new Comparator<Object1>() {
                @Override
                public int compare(Object1 a1, Object1 a2) {
                    SimpleDateFormat format = new SimpleDateFormat("dd.MM.yyyy");
                    Date date1;
                    Date date2;
                    if(a1.name.equals(a2.name)) {
                        try {
                            date1 = format.parse(a1.date);
                            date2 = format.parse(a2.date);
                        } catch (ParseException e) {
                            throw new IllegalArgumentException("Could not parse date!", e);
                        }
                        return date1.compareTo(date2);
                    }

                    else
                        return a1.name.compareTo(a2.name) ;
                }

            });

3 个答案:

答案 0 :(得分:0)

最好的方法是让不同类型的对象从同一个类继承/实现相同的接口。如果无法做到这一点,请尝试以下方法:

    List<Object> combinedList = new ArrayList<>();
    combinedList.addAll(array1);
    combinedList.addAll(array2);
    Collections.sort(combinedList, new Comparator<Object>() {
        public int compare(Object o1, Object o2) {
            String name1 = o1 instanceof Type1 ? ((Type1) o1).getName()
                    : ((Type2) o1).getName();
            String name2 = o2 instanceof Type1 ? ((Type1) o2).getName()
                    : ((Type2) o2).getName();

            Date date1 = o1 instanceof Type1 ? ((Type1) o1).getDate()
                    : ((Type2) o1).getDate(); 
            Date date2 = o2 instanceof Type1 ? ((Type1) o2).getDate()
                    : ((Type2) o2).getDate(); 
            int comparedNames = name1.compareTo(name2);
            return comparedEvents != 0 ? comparedEvents : date1.compareTo(date2);
        }
    });

答案 1 :(得分:0)

考虑创建一个适配器类来包装原始对象的实例,对包装的对象进行排序,然后从包装器中提取原始对象。例如,如果FirstThingy和SecondThing表示没有公共继承或接口的原始对象类:

public class FirstThingy {
    private String name;
    private java.util.Date date;
    private double value;

    public FirstThingy(String aName, java.util.Date aDate, double aValue) {
        this.name = aName;
        this.date = aDate;
        this.value = aValue;
    }

    public String getName() { return this.name; }
    public java.util.Date getDate() { return this.date; }
    public double getValue() { return value; }

    @Override 
    public String toString() {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
        return String.format("%s(name = \"%s\", date = \"%s\", value = %s)",
                             getClass().getSimpleName(),
                             getName(),
                             sdf.format(getDate()),
                             Double.toString(getValue()));
    }
}


public class SecondThingy {
    private String name;
    private java.util.Date date;
    private String email;

    public SecondThingy(String aName, java.util.Date aDate, String anEmail) {
        this.name = aName;
        this.date = aDate;
        this.email = anEmail;
    }

    public String getName() { return this.name; }
    public java.util.Date getDate() { return this.date; }
    public String getEmail() { return email; }

    @Override 
    public String toString() {
        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("MM/dd/yyyy");
        return String.format("%s(name = \"%s\", date = \"%s\", value = %s)",
                             getClass().getSimpleName(),
                             getName(),
                             sdf.format(getDate()),
                             getEmail());
    }
}

创建一个适配器类来包装原始实例:

public abstract class ThingyAdapter<T> implements Comparable<ThingyAdapter> {
    abstract public String getName();
    abstract public java.util.Date getDate();
    abstract public T getThingy();

    public static ThingyAdapter<FirstThingy> newAdapter(FirstThingy thingy) { return new FirstAdapter(thingy); }
    public static ThingyAdapter<SecondThingy> newAdapter(SecondThingy thingy) { return new SecondAdapter(thingy); }

    @Override
    public int compareTo(ThingyAdapter adapter) {
        if (adapter == null) { return 1; }
        if (this == adapter) { return 0; }
        int comparison = getName().compareTo(adapter.getName());
        if (comparison == 0) { return getDate().compareTo(adapter.getDate()); }
        return comparison;
    }

    @Override public String toString() { return getThingy().toString(); }
}

现在为每个原始类实现包装器:

public class FirstAdapter extends ThingyAdapter<FirstThingy> {
    private final FirstThingy thingy;

    public FirstAdapter(FirstThingy thingy) { this.thingy = thingy; }
    @Override public String getName() { return this.thingy.getName(); }
    @Override public java.util.Date getDate() { return this.thingy.getDate(); }
    @Override public FirstThingy getThingy() { return this.thingy; }
}

public class SecondAdapter extends ThingyAdapter<SecondThingy> {
    private final SecondThingy thingy;

    public SecondAdapter(SecondThingy thingy) { this.thingy = thingy; }
    @Override public String getName() { return this.thingy.getName(); }
    @Override public java.util.Date getDate() { return this.thingy.getDate(); }
    @Override public SecondThingy getThingy() { return this.thingy; }
}

然后,您的程序实现合并列表,排序,然后处理结果可能如下所示:

public class MixedLists {

    private static java.util.Date date(int year, int month, int day) {
        java.util.Calendar calendar = java.util.Calendar.getInstance();
        calendar.set(year, month, day);
        return calendar.getTime();
    }

    public static void main(String[] args) {
        int status = 0;

        try {
            FirstThingy[] firstArray = {
                new FirstThingy("Thomas", date(1964,9,30), 10.5d),
                new FirstThingy("George", date(1970, 1, 12), 16.1d),
                new FirstThingy("Conrad", date(2001, 5, 10), 34.1d),
                new FirstThingy("Fred", date(1980, 9, 22), 25.3d),
                new FirstThingy("George", date(1970, 1, 12), 19.9d)
            };

            SecondThingy[] secondArray = {
                new SecondThingy("Karl", date(1964,9,30), "karl@host.com"),
                new SecondThingy("Fred", date(1990, 6, 15), "fredrick@host.com"),
                new SecondThingy("Paul", date(1970, 1, 12), "paul@host.com"),
                new SecondThingy("Fred", date(1970, 1, 12), "fred@host.com"),
                new SecondThingy("Conrad", date(2001, 5, 10), "conrad@host.com")
            };

            java.util.ArrayList<ThingyAdapter> list = new java.util.ArrayList<ThingyAdapter>();
            for(FirstThingy thingy : firstArray) {
                list.add(ThingyAdapter.newAdapter(thingy));
            }

            for(SecondThingy thingy : secondArray) {
                list.add(ThingyAdapter.newAdapter(thingy));
            }

            java.util.Collections.sort(list);
            for(ThingyAdapter thingy : list) {
                System.out.println(thingy.toString());
            }
        } catch (Throwable thrown) {
            status = -1;
            thrown.printStackTrace(System.out);
        } finally {
            System.exit(status);
        }
    }
}

执行结果:

FirstThingy(name = "Conrad", date = "06/10/2001", value = 34.1)
SecondThingy(name = "Conrad", date = "06/10/2001", value = conrad@host.com)
SecondThingy(name = "Fred", date = "02/12/1970", value = fred@host.com)
FirstThingy(name = "Fred", date = "10/22/1980", value = 25.3)
SecondThingy(name = "Fred", date = "07/15/1990", value = fredrick@host.com)
FirstThingy(name = "George", date = "02/12/1970", value = 16.1)
FirstThingy(name = "George", date = "02/12/1970", value = 19.9)
SecondThingy(name = "Karl", date = "10/30/1964", value = karl@host.com)
SecondThingy(name = "Paul", date = "02/12/1970", value = paul@host.com)
FirstThingy(name = "Thomas", date = "10/30/1964", value = 10.5)

答案 2 :(得分:0)

据我所知,我认为最适合您的解决方案是使用单个列表,该列表可以包含不同的对象但具有相同的父类。 我会更好地解释。 由于您的所有对象都有一个共同的字段名称和日期,因此您可以这样做:

public class CommonBaseClass {
    public String name;
    public long date;
}

然后您可以根据需要多次扩展此对象:

public class MyEvent extends CommonBaseClass {
    public String actor;
    public String city;
}

public class MyEvent2 extends CommonBaseClass {
    public String type;
    public int nemberOfFriends;
}

现在您可以创建一个这样的列表并添加MyEvent和MyEvent2对象:

ArrayList<CommonBaseClass> myList = new ArrayList<CommonBaseClass>();
myList.add(new MyEvent("myEvent", "Rome"));
myList.add(new MyEvent2("Concert", 10));

从现在开始,您可以将myList威胁CommonBaseClass列为if(myList.get(index) instanceof MyEvent) { MyEvent event = ((MyEvent) myList.get(index)); .....do something with it...... }else { MyEvent2 event = ((MyEvent2) myList.get(index)); .....do something with it...... } 个对象,并按照之前的方式对其进行排序。

<强>更新 如果要从列表中检索对象,可以这样做:

{{1}}