简体   繁体   中英

Sorting ArrayList by specified values in List

For eg I have an array:

String[] Array1 = 
        {"15", "1", "D1", "Wine",       "1", "0", 
         "15", "3", "D3", "Tap water",  "2", "2",
         "15", "1", "M1", "Fish",       "3", "0",
         "9", "5", "D4", "Coffee",     "2", "2",
         "9", "2", "P2", "Cake",       "2", "1" 
        };
someList.addAll(Arrays.asList(Array1));

I want to sort some type of ArrayList similar to this in numerical order according to the second value in each line ie 1,3,1,5,2 into 1,1,2,3,5 , while keeping the other variable in same line intact. I am not allowed to make another class to store these variables in order. Does anyone know how I can sort them like that?

You used the wrong data structure. Arrays are used for multiple variables of the same type containing the same kind of information .

I suggest you create a class and create an array containing objects of that class, something like this:

Drink.class

class Drink{
    private int a;
    private int b;
    private String c;
    private String drinkName;
    private int d;
    private int e;

    public Drink(int a,int b,String c,String drinkName,int d,int e){
        this.a=a;
        this.b=b;
        this.c=c;
        this.drinkName=drinkName;
        this.d=d;
        this.e=e;
    }

        // Getters and setters here
        public String getDrinkName(){
            return drinkName;
        }
        // .....
}

And then in your main class:

class MainClass{
    List<Drink> drinks;
    public static void main(String[] args){
        drinks = new ArrayList<>();
        drinks.add(new Drink(15,1,"D1","Wine",1,0));
        drinks.add(new Drink(15,3,"D3","Tap Water",2,2));
        // Etc...
        // You can retrieve elements using .get(index) and then use getters on it to retrieve informations
        System.out.println(drinks.get(0).getDrinkName());
        Collections.sort(drinks,new Comparator<Drink>(){
            @Override
            public int compare(Drink d1, Drink d2){
                // Edit this method as you need
                return d1.getA().compareTo(d2.getA());
            }

        });
    }
}

You will not be able to sort the elements easily if you store all elements as String values into array . Rather you can make use of OOP and define the custom type (class) called MyCustomData and then load data as objects.

So, you need to follow the below steps:

(1) Define the custom class MyCustomData

(2) Create objects for MyCustomData and load them into array.

(3) Now, Sort the array using Comparator

You can refer the below code with comments:

MyCustomData class (Name this class properly):

public class MyCustomData {
        private int value1;//holds your element to be sorted
        //other values //define other values to hold fish, etc..

        public int getValue1() {
            return value1;
        }

        public void setValue1(int value1) {
            this.value1 = value1;
        }
    }

Sorting the Array of MyCustomData:

public static void main(String[] args) {

        MyCustomData[] myCustomDataArray = new MyCustomData[5];
        MyCustomData myCustomData1 = new MyCustomData();
        myCustomData1.setValue1(1);
        myCustomDataArray[0] = myCustomData1;
        //Create and Load other objects myCustomDataArray[1] , [2], ....into array 

        Comparator<MyCustomData> comp = (MyCustomData data1, MyCustomData data2) 
                             -> data1.getValue1()-data2.getValue1();
        Arrays.stream(myCustomDataArray).sorted(comp);
}

If you create some helpful methods and a comparator you could use a classic sort method like bubble-sort:

public static void main(String[] args) {    
    String[] array1 = 
        {"15", "1", "D1", "Wine",       "1", "0", 
         "15", "3", "D3", "Tap water",  "2", "2",
         "15", "1", "M1", "Fish",       "3", "0",
         "9", "5", "D4", "Coffee",     "2", "2",
         "9", "2", "P2", "Cake",       "2", "1" 
        };
    Comparator<String[]> comparator = new Comparator<String[]>(){
        @Override
        public int compare(String[]a1, String[] a2) {
            return Integer.valueOf(a1[1]).compareTo(Integer.valueOf(a2[1]));
        }
    };
    int lineLength=6;
    bubbleSort(array1,lineLength,comparator);
    System.out.println(Arrays.toString(array1));
}
//classic bubble-sort algorithm
public static void bubbleSort(String[]array1,int lineLength,Comparator<String[]> comparator){
    int numRow=array1.length/lineLength;
    for(int i=0;i<numRow;i++){
        for(int j=i+1;j<numRow;j++){
            String[] extractArrayI = extractArray(array1, i, lineLength);
            String[] extractArrayJ = extractArray(array1, j, lineLength);
            if(comparator.compare(extractArrayI, extractArrayJ)>0){
                swichLines(array1,i,j,lineLength);
            }
        }
    }
}
//extract i-th row
public static String[] extractArray(String[]array,int i, int lineLength){
    String [] a= new String[lineLength];
    System.arraycopy(array, i*lineLength, a, 0, lineLength);
    return a;
}
//Switch line i,j
public static void swichLines(String[]array,int i, int j,int lineLength){
    String [] temp = new String[lineLength];
    System.arraycopy(array, i*lineLength, temp, 0, lineLength);
    System.arraycopy(array, j*lineLength, array, i*lineLength, lineLength);
    System.arraycopy(temp, 0, array, j*lineLength, lineLength);
} 

UPDATE: using List<String> instead of String[] :

public static void main(String[] args) {  
    String[] array1 = 
            {"15", "1", "D1", "Wine",       "1", "0", 
             "15", "3", "D3", "Tap water",  "2", "2",
             "15", "1", "M1", "Fish",       "3", "0",
             "9", "5", "D4", "Coffee",     "2", "2",
             "9", "2", "P2", "Cake",       "2", "1" 
            };
    List<String> list = Arrays.asList(array1);
    Comparator<List<String>> comparator = new Comparator<List<String>>(){
        @Override
        public int compare(List<String>a1, List<String> a2) {
            return Integer.valueOf(a1.get(1)).compareTo(Integer.valueOf(a2.get(1)));
        }
    };
    int lineLength=6;
    System.out.println(list.toString());
    bubbleSort(list,lineLength,comparator);
    System.out.println(list.toString());
}
//classic bubble-sort algorithm
public static void bubbleSort(List<String> list,int lineLength,Comparator<List<String>> comparator){
    int numRow=list.size()/lineLength;
    for(int i=0;i<numRow;i++){
        for(int j=i+1;j<numRow;j++){
            List<String> extractArrayI = extractArray(list, i, lineLength);
            List<String> extractArrayJ = extractArray(list, j, lineLength);
            if(comparator.compare(extractArrayI, extractArrayJ)>0){
                swichLines(list,i,j,lineLength);
            }
        }
    }
}
//extract i-th row
public static List<String> extractArray(List<String> list,int i, int lineLength){
    return list.subList(i*lineLength, i*lineLength+lineLength);
}
//Switch line i,j
public static void swichLines(List<String>list,int i, int j,int lineLength){
    List<String>tempI = new ArrayList<String>(list.subList(i*lineLength, i*lineLength+lineLength));
    List<String>tempJ = new ArrayList<String>(list.subList(j*lineLength, j*lineLength+lineLength));
    replaceSublist(list,tempJ,i,lineLength);
    replaceSublist(list,tempI,j,lineLength);
}
//replace sublist
private static void replaceSublist(List<String> list, List<String> temp, int line, int lineLength) {
    for (int k=0; k<lineLength; k++)
    {
        list.set(line*lineLength+k, temp.get(k));
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM