Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting text with some rules

Tags:

java

sorting

I have a arraylist as follows

100 AAA 500-1 Lorem Ipsum
100 BBB 500-2 Lorem Ipsum
101 AAA 500-1 Lorem Ipsum
101 AAA 500-2 Lorem Ipsum
100 BBB 500-3 Lorem Ipsum

I want this to be sorted as

101 AAA 500-1 Lorem Ipsum
101 AAA 500-2 Lorem Ipsum
100 AAA 500-1 Lorem Ipsum
100 BBB 500-2 Lorem Ipsum
100 BBB 500-3 Lorem Ipsum

First, descending by number (101, 100).

Second, ascending by three letter word (AAA, BBB).

Third, ascending by third column (500-1, 500-2, 500-3)

I can split each element by space and get individual word and sort. But can anyone please help me with any other way or known algorithm? Please let me know if you need more information.

Thank you in advance.

like image 755
emeh Avatar asked Feb 10 '26 20:02

emeh


2 Answers

Creation of a Comparator will solve your problem. You should implement something like this:

public class MyComparator implements Comparator<MyObject> {    
  public int compare(MyObject o1, MyObject o2) {
    if (o1 == null || o2 == null) {
      throw new NullPointerException();
    }    
    if (o1.getValue1() != o2.getValue1()) {
      return Integer.compare(o1.getValue1(), o2.getValue1());
    }    
    return Integer.compare(o1.getValue2(), o2.getValue2());
  }
}

Of course there are more ways to solve this problem, e.g., you can implement your own sorting algorithm. However, I think that the use of Comparator is the right "java-way" to solve it.

like image 73
Martin Dvoracek Avatar answered Feb 12 '26 14:02

Martin Dvoracek


I assume that you have a Collection of String.

I will be using Comparator to solve it.

    List<String> myCollection = new ArrayList<String>();

    Collections.sort(myCollection, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            // splitting it with space character
            String[] split1 = o1.split(" ");
            String[] split2 = o2.split(" ");

            int i1 = Integer.parseInt(split1[0]);
            int i2 = Integer.parseInt(split2[0]);

            int diff = (i2 - i1);

            if(diff != 0){ // if two integer are equal
                return diff;
            }else{
                return split2[1].compareTo(split1[1]);
            }
        }
    });
like image 32
Talha Ahmed Khan Avatar answered Feb 12 '26 16:02

Talha Ahmed Khan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!