1

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? :)

2 Answers 2

1

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);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Hey, that seems to be a very cool solution :) . But I still don't know how to sort all the 'JKL's to the begin. The current output with your solution is: [ABC, ABC, ABC, JKL, JKL, JKL, DEF, DEF, GHI, GHI, MNO, MNO]
@Kody - Just remove the "ABC" from the 'specials'.
That is awesome! Thank you! :)
1

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);
    }
}

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.