Kody
Kody

Reputation: 1244

Sort custom string first

I have an unsorted List ... let's say it's ArrayList which contains Strings that can occur multiple times. How can I achive to sort the occurence of a very certain string(s) first. The rest of the entries can remain in the given order.

eg. certain string that has to be on top: 'JKL'

unsorted: { DEF, ABC, JKL, GHI, ABC, DEF, JKL, MNO, GHI, ABC, MNO, JKL }

sorted: { JKL, JKL, JKL, DEF, ABC, GHI, ABC, DEF, MNO, GHI, ABC, MNO }

Any suggestions? :)

Upvotes: 1

Views: 63

Answers (2)

OldCurmudgeon
OldCurmudgeon

Reputation: 65889

Use a Comparator but be careful to ensure that the comparator is consistent.

public void test() {
    List<String> strs = Arrays.asList(new String[]{"DEF", "ABC", "JKL", "GHI", "ABC", "DEF", "JKL", "MNO", "GHI", "ABC", "MNO", "JKL"});
    // All these are special and should appear at the front of the list.
    Set<String> specials = new HashSet<>(Arrays.asList("ABC", "JKL"));
    strs.sort((String o1, String o2) -> {
        if (specials.contains(o1) == specials.contains(o2)) {
            // Both special or both normal - just compare.
            return o1.compareTo(o2);
        } else if (specials.contains(o1)) {
            // First is special!
            return -1;
        } else {
            // Second is special.
            return 1;
        }
    });
    System.out.println(strs);
}

Upvotes: 1

RaminS
RaminS

Reputation: 2239

You can delete every JKL element from the list (except if the first element is JKL, since that would be unnecessary), and add a new one to the beginning of the list. Let's say your list is called list:

for(int i = 1; i < list.length(); i++) { //no need to check if the first element is "JKL"
    if(list.get(i).equals("JKL")) {
        list.remove(i);
        list.add(0, "JKL");
    }
}

Make sure you remove it before adding it to the list. If you do it the other way, you would need to do list.remove(i+1);.

Edit: For a more general solution that involves other objects than strings that are better not deleted and recreated, you can store the element in a temporary variable before deleting it, and the putting it back in the beginning of the list:

for(int i = 1; i < list.length(); i++) {
    if(list.get(i).equals("JKL")) {
        String temp = list.get(i);
        list.remove(i);
        list.add(0, temp);
    }
}

Upvotes: 1

Related Questions