首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >反向收藏

反向收藏
EN

Stack Overflow用户
提问于 2016-03-17 04:01:44
回答 2查看 426关注 0票数 0

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

赛迪

卡尔

赛迪

卡尔

但我想把它们放在一起像:

赛迪

赛迪

卡尔

卡尔

我尝试了两次添加Collections.reverse (就像删除一样),但没有起作用。这是可能的还是我应该放弃?以下是我的当前代码:

代码语言:javascript
复制
    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.");
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-17 04:25:02

尝尝这个。

代码语言:javascript
复制
List<People> peopleListClone = peopleList.stream()
    .flatMap(s -> Stream.of(s, s))
    .collect(Collectors.toList());

而不是

代码语言:javascript
复制
ArrayList<People> peopleListClone = new ArrayList<People>();
peopleListClone.addAll(peopleList);
peopleListClone.addAll(peopleList);
票数 0
EN

Stack Overflow用户

发布于 2016-03-17 04:24:48

我仍然不太明白你想用你写出来的代码实现什么。如果这能帮助您理解克隆和逆转ArrayLists的方式,请告诉我。

代码语言:javascript
复制
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
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36051441

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档