反向收藏

时间:2016-03-17 04:01:45

标签: java arraylist collections

我试图反转我的集合,它由两个ArrayList(具有相同的对象)组成。它分别反转两个ArrayList,如下所示:

赛迪

卡尔

赛迪

卡尔

但是我希望它们像:

一样排序

赛迪

赛迪

卡尔

卡尔

我尝试过两次添加Collections.reverse(就像我删除的那样),但是没有用。是否有可能或者我应该放弃?这是我目前的代码:

    List<People> peopleList = new ArrayList<People>();
    Student student1 = new Student("Diana", "Carter", new Date("09/15/1992"), 111222333);
    peopleList.add(student1);
    Faculty faculty1 = new Faculty("Clark", "Kent", new Date("05/22/1990"), 199242003,
            323232);
    peopleList.add(faculty1);
    Staff staff1 = new Staff("Bruce", "Wayne", new Date("01/01/1993"),  161257235,
            100000);
    peopleList.add(staff1);
    Collections.addAll(peopleList);

    ArrayList<People> peopleListClone = new ArrayList<People>();
    peopleListClone.addAll(peopleList);
    peopleListClone.addAll(peopleList);

    Collections.addAll(peopleListClone);
    DisplayPeople(peopleListClone, "////////////////// People list clone     initialized.");

    peopleListClone.remove(student1);
    peopleListClone.remove(student1);
    DisplayPeople(peopleListClone, "////////////////// People list after student elements removed.");

    Collections.reverse(peopleListClone);
    Collections.reverse(peopleListClone);
    DisplayPeople(peopleListClone, "////////////////// People list clone sorted in reverse.");

2 个答案:

答案 0 :(得分:0)

我仍然没有完全了解你用你编写的代码实现的目标。如果这有助于您了解克隆并以任何方式撤消var base_url = "<?php echo base_url();?>";,请与我们联系。

ArrayLists

答案 1 :(得分:0)

试试这个。

List<String> list = new ArrayList<String>();
list.add("apple");
list.add("ball");
list.add("cat");
list.add("dog");            // [apple, ball, cat, dog]  
Collections.reverse(list);
System.out.println(list);   // [dog, cat, ball, apple]

List<String> list2 = new ArrayList<String>();
list2.addAll(list);         // MAKING A HARD COPY

Collections.reverse(list2); // REVERSING THE HARD COPY
System.out.println(list2);  // [apple, ball, cat, dog]  REVERSED HARD COPY
System.out.println(list);   // [dog, cat, ball, apple] STILL THE SAME ORIGINAL

而不是

List<People> peopleListClone = peopleList.stream()
    .flatMap(s -> Stream.of(s, s))
    .collect(Collectors.toList());