从未排序的ArrayList创建排序数组

时间:2016-01-02 14:54:15

标签: java arrays for-loop arraylist

我有一个ArrayList,里面填充了类结果的对象,每个结果都有一个名为value的属性。我现在想要创建一个数组,其中填充了与ArrayList中相同的内存位置的引用,但现在按顺序将具有最高值的对象放在第一个位置,第二个位置中的第二个位置,依此类推。 / p>

我在这里搜索过,但没有找到任何其他类似的帖子。

1 个答案:

答案 0 :(得分:0)

使用Gauava或lambda表达式有多种方法可以解决它。

希望这个实现解决你的问题。

package com;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class TestDemo {


 public static void main(String[] args) {


  List < HockeyPlayer > players = new ArrayList < HockeyPlayer > ();
  HockeyPlayer obj1 = new HockeyPlayer();
  obj1.goalsScored = 22;
  players.add(obj1);
  HockeyPlayer obj2 = new HockeyPlayer();
  obj2.goalsScored = 11;
  players.add(obj2);
  HockeyPlayer obj3 = new HockeyPlayer();
  obj3.goalsScored = 111;
  players.add(obj3);
  HockeyPlayer obj4 = new HockeyPlayer();
  obj4.goalsScored = 3;
  players.add(obj4);

  Collections.sort(players, new Comparator < HockeyPlayer > () {
   @Override public int compare(HockeyPlayer player1, HockeyPlayer player2) {
    return player1.goalsScored - player2.goalsScored;
   }

  });

  for (int i = 0; i < players.size(); i++) {
   System.out.println(players.get(i).goalsScored);
  }

  HockeyPlayer array[] = new HockeyPlayer[players.size()];

  players.toArray(array); // contains reference 


  for (int i = 0; i < array.length; i++) {
   System.out.println(array[i].goalsScored);
  }


 }

}

class HockeyPlayer {
 public int goalsScored;

}