1

If I have an ArrayList as the following:

["a 100", "b 32", "t 54", "u 1"] (numbers and letter are separated by space in each cell of the array list).

How can I sort it by numbers keeping each number with its corresponding letter?.

6
  • 4
    Show us what have you tried? Commented Apr 16, 2016 at 19:08
  • 1
    What are you trying to achieve? A primary search by the string part and the secondary by the integer part? Commented Apr 16, 2016 at 19:12
  • 1
    Google java comparator. That is how you can sort a list by some custom property or definition of order. Commented Apr 16, 2016 at 19:15
  • is that pattern always the same?? can we assume all elements in the list are composed as "1Char+space+Anumber" Commented Apr 16, 2016 at 19:15
  • 1
    It looks like your list shouldn't be storing Strings but objects of your own class which could store String and int. This would give you a lot of flexibility when you would like to search/sort based on one of these values. Commented Apr 16, 2016 at 19:19

6 Answers 6

3

This looks like you are trying to implement object oriented programming using strings. Luckily, Java has already done this.

So, do something like this instead:

public class MyClass implements Comparable<MyClass> {
    private final String aString; //could be char perhaps..
    private final Integer anInteger;

    public MyClass(final String aString, final Integer anInteger) {
        this.aString = aString;
        this.anInteger = anInteger;
    }

    public String getAString() { return aString; }
    public Integer getAnInteger() { return anInteger; }

    public String toString() { return anInteger + " " + aString }

    //comparison by number
    public int compareTo(final MyClass other) {
        return anInteger.compareTo(other.anInteger);
    }
}

Then, you use it like this:

final List<MyClass> myClasses = new ArrayList<>();
myClasses.add(new MyClass("a", 100));
myClasses.add(new MyClass("b", 32));
myClasses.add(new MyClass("t", 54));
myClasses.add(new MyClass("u", 1));

Collections.sort(myClasses);
Sign up to request clarification or add additional context in comments.

Comments

1

You can simply use swapping method just like in regular arrays. The only difference is that we use set(index, "value") method to update a specific string at specified index.

public static void sort (ArrayList<String> arr){    

    int N = arr.size();
    int E = N-1;
    String temp;
    boolean flag = true;

    while(flag){
        flag=false;

        for(int a = 0 ; a < E ; a++){
            if(Integer.parseInt(arr.get(a).substring(arr.get(a).indexOf(" ")+1)) > 
               Integer.parseInt(arr.get(a+1).substring(arr.get(a+1).indexOf(" ")+1))) {

                temp=arr.get(a);
                arr.set(a, arr.get(a+1));   
                arr.set(a+1, temp);

                flag=true;
            }   
        }
        E--;    
    }}

The sorting algorithm is bubble sort. I have used it due to simplicity. You can use any other sorting algorithm if you want.

Then, you can call the sort() function in main method:

    public static void main(String[] args) {

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

    arr.add("a 98");
    arr.add("a 23");
    arr.add("c 11");

    sort(arr);
}

1 Comment

Wow, that is slow.
1

Use a custom comparator to sort the list.

List<String> yourList = Arrays.asList("a 100", "b 32", "t 54", "u 1");
yourList.sort((entry1, entry2) -> {
    int number1 = Integer.parseInt(entry1.split(" ")[1]);
    int number2 = Integer.parseInt(entry2.split(" ")[1]);

    return Integer.compare(number1, number2);
});

Regards

Comments

1
import static java.lang.Integer.*;

Just import static Integer methods and you'll get the most compact Comparator<String> for your purpose.

(a, b) -> compare(valueOf(a.split(" ")[1]), valueOf(b.split(" ")[1]));

2 Comments

import statements ending with * are poor practice. Better to use import static java.lang.Integer.valueOf; instead.
@VGR, yes, I know that, but the love for the shortest answers will kill me :) By the way, here we should have 2 static imports for compare and valueOf methods.
1

Assuming the elements in the list are the same pattern:

then you can do

public static void main(String[] args) {
    //  ["a 100", "b 32", "t 54", "u 1"]
    List<String> myList = new ArrayList<>();
    myList.add("a 100");
    myList.add("b 32");
    myList.add("t 54");
    myList.add("u 1");
    System.out.println("List unsorted" + myList);
    Collections.sort(myList, new Comparator<String>() {

        @Override
        public int compare(String o1, String o2) {
            try {
                int a1 = Integer.parseInt(o1.substring(2));
                int a2 = Integer.parseInt(o2.substring(2));
                return Integer.compare(a1,a2);
            } catch (NumberFormatException ex) {
                return 0;
            }
        }
    });
    System.out.println("List sorted" + myList);
}

Comments

0

In Java 8, Comparator has a handful of static and default methods that make it easy to create custom comparators. For instance, you could create one that splits each string and converts the second word to an integer.

list.sort(Comparator.comparingInt(
    s -> Integer.parseInt(s.split(" ")[1])
));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.