繁体   English   中英

迭代并组合两个不同对象的排序数组列表

[英]Iterate and combine two sorted arraylists of different objects

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

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

ArrayList2具有: event0 02.01,event2 05.10

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

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

我如何遍历2个arraylist并获取每个唯一事件及其在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) ;
                }

            });

最好的方法是让不同类型的对象继承自相同的类/实现相同的接口。 如果这不可能,请尝试以下操作:

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

考虑创建一个适配器类来包装原始对象的实例,对包装的对象进行排序,然后从包装器中提取原始对象。 例如,如果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)

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

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......
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM