如何对arraylist进行排序并同时获取索引号

时间:2017-04-26 20:41:20

标签: java arraylist

我对这些元素进行反向排序,我希望同时按索引进行相同的排序

排序索引号后的s1.deposit.get(0) = 100就像是2,我希望Tom在开头的索引号为0时得到2。我怎么能这样做?

s1.deposit.add(100);
s1.deposit.add(75);
s1.deposit.add(1890);
s1.deposit.add(25);
s1.deposit.add(360);

acc.named.add("Tom");
acc.named.add("John");
acc.named.add("Elena");
acc.named.add("Ralph");
acc.named.add("Carl");

Collections.sort(s1.deposit, Collections.reverseOrder());
int i = 0;
for(int counter: s1.deposit)  
    System.out.println(counter + " "+ acc.named.get(i));
    i++;
}

1 个答案:

答案 0 :(得分:0)

最好的解决方案是让List<Person>名为people,而不是两个单独的列表s1.depositacc.namedPerson类可以如下:

public class Person {

    private String name;

    private int deposit;

    // TODO: constructor accepting both fields, getters and setters
}

以及人员名单:

List<Person> people = new ArrayList<>();

people.add(new Person("Tom", 100));
people.add(new Person("John", 75));
people.add(new Person("Elena", 1890));
people.add(new Person("Ralph", 25));
people.add(new Person("Carl", 360));

然后,对该集合进行排序很简单:

Collections.sort(
    people,
    Comparator.comparing(Person::getDeposit).reversed());

但是,如果不能选择创建Person这样的类,您仍然可以在TreeMap的帮助下完成所需的操作,Map.computeIfAbsent按键对条目进行排序:

Map<Integer, List<Integer>> indicesMap = 
    new TreeMap<>(Comparator.naturalOrder().reversed());

for (int i = 0; i < s1.deposit.size(); i++) {
    Integer deposit = s1.deposit.get(i);
    indicesMap.computeIfAbsent(deposit, k -> new ArrayList<>()).add(i);
}

我在这里使用Stream.flatMap方法。

填充完地图后,您只需要遍历其值:

indicesMap.values().stream()
    .flatMap(Collection::stream)
    .map(acc.names::get)
    .forEachOrdered(System.out::println);

我正在流式传输地图的值(列表),然后我使用Stream.map方法将列表流按顺序展平为包含所有列表元素的流。然后我通过https://developers.google.com/maps/web/方法将这些索引转换为acc.names列表中的相应名称,最后打印出来。

相关问题