我希望对整数的arraylist进行排序,我需要帮助吗?
我被告知我需要实现比较器或者类比,然后使用collection.sort按顺序对列表列表进行排序......
ArrayList<ArrayList<Integer>> g = new ArrayList<ArrayList<Integer>>()
If you look at the list of list as the following example:
C1 – 5,4,10
C2 – 3,2,1
C3 – 7,8,6
First it will be sorted like this:
C1 – 4,5,10
C2 – 1,2,3
C3 – 6,7,8
Then it will be sorted like this
C1 – 1,2,3
C2 – 4,5,6
C3 – 7,8,10
答案 0 :(得分:15)
没有错误检查空列表,但现在是。
List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4),
Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6));
for (List<Integer> l : list) {
Collections.sort(l);
}
Collections.sort(list, new Comparator<List<Integer>>() {
public int compare(List<Integer> o1, List<Integer> o2) {
return o1.get(0).compareTo(o2.get(0));
}
});
System.out.println(list);
使用Java 8,它变得更加简洁:
List<List<Integer>> list = Arrays.asList(Arrays.asList(10, 5, 4),
Arrays.asList(3, 2, 1), Arrays.asList(7, 8, 6));
list.forEach(Collections::sort);
Collections.sort(list, (l1, l2) -> l1.get(0).compareTo(l2.get(0)));
System.out.println(list);
答案 1 :(得分:6)
您可以单独对每个列表进行排序。 Collections.sort(collection)
将自动按升序对整数进行排序。
答案 2 :(得分:1)
如果排序没有你需要的东西你可以试试这个算法:
package drawFramePackage;
import java.awt.geom.AffineTransform;
import java.util.ArrayList;
import java.util.ListIterator;
import java.util.Random;
public class QuicksortAlgorithm {
ArrayList<AffineTransform> affs;
ListIterator<AffineTransform> li;
Integer count, count2;
/**
* @param args
*/
public static void main(String[] args) {
new QuicksortAlgorithm();
}
public QuicksortAlgorithm(){
count = new Integer(0);
count2 = new Integer(1);
affs = new ArrayList<AffineTransform>();
for (int i = 0; i <= 128; i++){
affs.add(new AffineTransform(1, 0, 0, 1, new Random().nextInt(1024), 0));
}
affs = arrangeNumbers(affs);
printNumbers();
}
public ArrayList<AffineTransform> arrangeNumbers(ArrayList<AffineTransform> list){
while (list.size() > 1 && count != list.size() - 1){
if (list.get(count2).getTranslateX() > list.get(count).getTranslateX()){
list.add(count, list.get(count2));
list.remove(count2 + 1);
}
if (count2 == list.size() - 1){
count++;
count2 = count + 1;
}
else{
count2++;
}
}
return list;
}
public void printNumbers(){
li = affs.listIterator();
while (li.hasNext()){
System.out.println(li.next());
}
}
}
答案 3 :(得分:0)
这对我有用
Collections.sort(list, new Comparator<List<Integer>>() {
public int compare(List<Integer> o1, List<Integer> o2) {
int min = Math.min(o1.size(),o2.size());
for(int i=0;i<min;i++)
{
if(o1.get(i)!=o2.get(i))
{
return o1.get(i).compareTo(o2.get(i));
}
}
return (o1.size()<=o2.size())? -1:1;
}
});