Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

android - 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!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
   }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...