简体   繁体   中英

how to sort Arraylist of string having integer values in java

I am having string list which consists of integer values. i just want to sort in ascending as well as in descending order.

ArrayList<String> a = new ArrayList<String>();
a.add("1435536000000");
a.add("1435622400000");

System.out.println("Before : " + a);
Collections.sort(a, new ComparatorOfNumericString());
System.out.println("After : " + a);

My ComparatorOfNumericString class is -

public class ComparatorOfNumericString implements Comparator<String> {

    @SuppressLint("NewApi")
    @Override
    public int compare(String lhs, String rhs) {
        int i1 = Integer.parseInt(lhs);
        int i2 = Integer.parseInt(rhs);
        return Integer.compare(i1, i2);
    }

}  

Any one having idea how to sort this strings having integer values in java?

Thanks a lot!! in Advance!!

The better way will be to add integers/long in to the ArrayList and then sorting it using Collections.sort(a) method.

If you still want to using String, you will need to make some modifications. Please find below code for the same:

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

public class Input implements Comparator<String>{
    public static void main(String[] args) {
        ArrayList<String> a = new ArrayList<String>();
        a.add("1435536000000");
        a.add("1435622400000");
        a.add("1");
        a.add("10");
        a.add("20");
        a.add("15");
        a.add("1435622400010");

        System.out.println("Before : " + a);
        Collections.sort(a, new Input());
        System.out.println("After : " + a);
          }

    public int compare(String lhs, String rhs) {
    long i1 = Long.parseLong(lhs);
    long i2 = Long.parseLong(rhs);
    return (int) (i1-i2);
   }

}

Try using :

Collections.sort(a);

Without any Comparator. It will sort any String alphabetically so logically it will serve for integer String too.

You can use this methods to sorting the Strings.

Collections.sort(arraylist);// for ascending order
Collections.sort(arraylist, Collections.reverseOrder());// for descending order.

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