1

I have a query. In my Java program I have a list of Strings, but I need to know how to sort them by an Integer contained in the Strings.

For Example:

ArrayList<String> list = new ArrayList<String>();

And in that list:

"PersonOne - 1234 seconds";
"PersonTwo - 5678 seconds";

I need to sort it by the numbers in each of the Strings. (There will be more items in the list).

Calan54
  • 267
  • 3
  • 13
  • If you happen to be comfortable in UNIX or Linux or the OS X Terminal, you might want to see that the command "sort -k3 -n" does what you're proposing. – minopret Apr 27 '14 at 10:01

5 Answers5

4

Start by transforming these strings into structured objects (Score, for example) containing a name (String) and a number of seconds (int). Then sort these objects by their number of seconds.

Parsing the string should be quite simple: you just need to find the index of the first dash, and the index of the first space after the dash. The String javadoc should help you find how to look for characters in a string, and how to extract substrings.

Note that unless these string come from some file or external resource that you have to parse, you shouldn't have to parse them in the first place. Use Score objects from the start, and only transform them as Strings when you have to print them.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
3

Use a custom comparator:

Collections.sort(list, new Comparator<String> () {
    public int compare(String a, String b) {
        return Integer.compare(Integer.parseInt(a.replaceAll("\\D", "")), Integer.parseInt(b.replaceAll("\\D", "")));
    }
});

You can even create a helper method to make the code cleaner:

Collection.sort(list, new Comparator<String> () {
    public int compare(String a, String b) {
        return Integer.compare(parse(a), parse(b));
    }
    int parse(String s) {
        return Integer.parseInt(s.replaceAll("\\D", ""));
    }
});
Bohemian
  • 412,405
  • 93
  • 575
  • 722
1

If your ArrayList element is of same format as PersonOne - 1234 seconds from this you can take the integers as,

String str = "PersonOne - 1234 seconds";
int integer = Integer.ParseInt(str.split("\\s")[2]);

take all integers in this format and sort it.

Rakesh KR
  • 6,357
  • 5
  • 40
  • 55
1

Since you have the strings in a list, you can write a custom comparator to do this. In the comparator, you need to extract the number. To do that, you can split on the - followed by splitting on the space.

public static void main(String[] args) {
    ArrayList<String> list = new ArrayList<String>();
    list.add("PersonTwo - 5678 seconds");
    list.add("PersonOne - 1234 seconds");
    list.add("PersonOnedf - 34 seconds");

    System.out.println("Initial : " + list); 
    Collections.sort(list, new Comparator<Object>() {
           @Override
           public int compare(Object arg0, Object arg1) {
               String s1 = (String)arg0;
               String s2 = (String)arg1;
               Integer n1 = Integer.parseInt(s1.split("-")[1].trim().split(" ")[0]);
               Integer n2 = Integer.parseInt(s2.split("-")[1].trim().split(" ")[0]);
               return (n1 < n2 ? -1 : 1);
           }
       });

     System.out.println("Sorted : " + list);

}


Output :
  Initial : [PersonTwo - 5678 seconds, PersonOne - 1234 seconds, PersonOnedf - 34 seconds]
  Sorted : [PersonOnedf - 34 seconds, PersonOne - 1234 seconds, PersonTwo - 5678 seconds]
axiom
  • 8,765
  • 3
  • 36
  • 38
0

I think your array should not be simply an array of String. Inseted you can create an class that contains tow variable name of type String and time of type Integer. after that you can create an array of objects of the class you created. Then you can sort you list based on the time in second.

the class will be some how like the following: (NOTE: the coded is not tested)

     public class SomeClassName
  {
    private String name;
    private Integer time;

    // Constructors

    public SomeClassName()
    {
    super();
    }

    public SomeClassName(String name, Integer time)
    {
    this.name=name;
    this.time=time;
    }
    // create setter and getter methods

    public void setName(String name)
    {
    this.name=name
    }

    public void setTime(Integer time)
    {
    this.time=time
    }

    public String getName()
    {
    return name;
    }
    public Integer getTime()
    {
    return time;
    }


}

then you can create an array of that class as follow:

ArrayList<SomeClassName> list = new ArrayList<SomeClassName>();
list.add( new SomeClassName("PersonOne" ,1234) );
list.add( new SomeClassName("PersonTwo",5678) );

to sort an ArrayList of objects based on some attribute you nee to use custom compactor. check this link: Sort ArrayList of custom Objects by property

Community
  • 1
  • 1
Salman
  • 1,236
  • 5
  • 30
  • 59