IdontwearString
IdontwearString

Reputation: 367

Sort Arraylist containing both numbers and letters

This is my current arraylist:

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

[102423;asd.com, 49952;qwe.com, 76933;rty.com, 199526;fgh.com, 139388;jkl, 25114;qaz, 155766;ghj.com, 321339;vbn.com, 210513;kol.com]

And I want to sort them by the numbers. Ive tried following:

Collections.sort(myArrayList)
for(String counter : myArrayList){
   System.out.println(counter);
  }

But its not working. Im thinking splitting then do Collections.sort but then I dont know how I will pair them togehter again.

Upvotes: 0

Views: 945

Answers (3)

user4910279
user4910279

Reputation:

The reason it's not working is that you have declared ArrayList of Strings. So, Collections.sort(YourArrayList) will sort it lexicographicall. So,you have to write your own Comparator to read the String and interpret it and compare.

So, Try this.

    List<String> list = Arrays.asList(
        "102423;asd.com", "49952;qwe.com", "76933;rty.com",
        "199526;fgh.com", "139388;jkl", "25114;qaz",
        "155766;ghj.com", "321339;vbn.com", "210513;kol.com");
    List<String> sorted = list.stream()
        .sorted(Comparator.comparing(s -> String.format("%0" + (20 - s.indexOf(';')) + "d%s", 0, s)))
        .collect(Collectors.toList());
    for (String s : sorted)
        System.out.println(s);

result is

25114;qaz
49952;qwe.com
76933;rty.com
102423;asd.com
139388;jkl
155766;ghj.com
199526;fgh.com
210513;kol.com
321339;vbn.com

This code sort list internally

00000000000000102423;asd.com
00000000000000049952;qwe.com
00000000000000076933;rty.com
00000000000000199526;fgh.com
00000000000000139388;jkl
00000000000000025114;qaz
00000000000000155766;ghj.com
00000000000000321339;vbn.com
00000000000000210513;kol.com

Upvotes: 0

Shiladittya Chakraborty
Shiladittya Chakraborty

Reputation: 4408

Use comparator like below :

public class CustomComparator implements Comparator<String> {
    @Override
    public int compare(String o1, String o2) {
        return o1.split(";")[0].compareTo(o2.split(";")[0]);
    }
}

Your sorting code would be just about like you wrote:

Collections.sort(arrayList, new CustomComparator());

Upvotes: 2

President James K. Polk
President James K. Polk

Reputation: 41956

Use the Collections.sort(List<T> list, Comparator<? super T> c) static method and supply a custom Comparator whose compare() method extracts the numeric prefix from the two elements and only compares those prefixes.

You could use String.split(";") to get the numeric prefix, for example.

Upvotes: 4

Related Questions