JAVAソート方法

8816 ワード

配列ソート
Arrays.sort(int[] x,int fromIndex,int fromIndex)
fromIndex fromIndex-1       

カスタムクラスソート
1.comparator、並べ替え方法を書き換える方法
package lx;

import java.util.Arrays;
import java.util.Comparator;

class point{
    int x,y;
    public point(){}
    public point(int x,int y){
        this.x = x;
        this.y = y;
    }
}
class mycompara implements Comparator{

    @Override
    public int compare(point o1, point o2) {
        // TODO Auto-generated method stub
        if(o1.x!=o2.x) return o1.x-o2.x;
        else return o1.y-o2.y;
    }
}

public class Sort { 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        point[] x=new point[5];
        for(int i = 0;i < x.length; i++){
            x[i] = new point();
        }
        x[0].x=1;x[0].y=2;
        x[1].x=4;x[1].y=2;
        x[2].x=6;x[2].y=2;
        x[3].x=2;x[3].y=3;
        x[4].x=1;x[4].y=7;
        Arrays.sort(x,new mycompara());
        for(int i=0;i<=4;i++){
            System.out.println(x[i].x+" "+x[i].y);
        }
    }
}

2.クラスをリロードする方法
package lx;

import java.util.Arrays;
import java.util.Comparator;

class point implements Comparable{
    int x,y;
    public point(){}
    public point(int x,int y){
        this.x = x;
        this.y = y;
    }
    @Override
    public int compareTo(point p1) {
        // TODO Auto-generated method stub
        if(x !=p1.x) return x-p1.x;
        else return y-p1.y;
    }
}
public class Sort { 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        point[] x=new point[5];
        for(int i = 0;i < x.length; i++){
            x[i] = new point();
        }
        x[0].x=1;x[0].y=2;
        x[1].x=4;x[1].y=2;
        x[2].x=6;x[2].y=2;
        x[3].x=2;x[3].y=3;
        x[4].x=1;x[4].y=7;
        Arrays.sort(x);
        for(int i=0;i<=4;i++){
            System.out.println(x[i].x+" "+x[i].y);
        }
    }
}

3.lambdaの方法
package lx;

import java.util.Arrays;
import java.util.Comparator;

class point{
    int x,y;
    public point(){}
    public point(int x,int y){
        this.x = x;
        this.y = y;
    }
}
public class Sort { 
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        point[] x=new point[5];
        for(int i = 0;i < x.length; i++){
            x[i] = new point();
        }
        x[0].x=1;x[0].y=2;
        x[1].x=4;x[1].y=2;
        x[2].x=6;x[2].y=2;
        x[3].x=2;x[3].y=3;
        x[4].x=1;x[4].y=7;
        Arrays.sort(x,(a,b)->(a.x!=b.x?a.x-b.x:a.y-b.y));   
        for(int i=0;i<=4;i++){
            System.out.println(x[i].x+" "+x[i].y);
        }
    }
}