I have a list of categories (in this example I used String
but in my project I have a model) which must be sorted like this:
- on top we should have 2 categories which have a fixed position in the list (in this example (C, F))
- at the bottom of the list we should have 3 categories which have a fixed position in the list (in this example (R, M, P))
- in the middle of the list we should have the rest of the elements sorted alphabetically
I want to know if there is a better solution than I used, for sorting the list this way. I do not want to use HashMap
, so if anyone could find a better solution for sorting the ArrayList
, I would highly appreciate it.
List<String> categories = new ArrayList<>();
categories.add("A");
categories.add("B");
categories.add("C");
categories.add("D");
categories.add("E");
categories.add("F");
categories.add("G");
categories.add("H");
categories.add("I");
categories.add("J");
categories.add("K");
categories.add("L");
categories.add("M");
categories.add("N");
categories.add("O");
categories.add("P");
categories.add("Q");
categories.add("R");
sortCategories(categories);
The sortCategories()
method is:
public void sortCategories(List<String> categories) {
List<String> topCategories = new ArrayList<>();
List<String> bottomCategories = new ArrayList<>();
for (String category : categories) {
if (category.equals("C")) {
topCategories.add(category);
break;
}
}
for (String category : categories) {
if (category.equals("F")) {
topCategories.add(category);
break;
}
}
for (String category : categories) {
if (category.equals("R")) {
bottomCategories.add(category);
break;
}
}
for (String category : categories) {
if (category.equals("M")) {
bottomCategories.add(category);
break;
}
}
for (String category : categories) {
if (category.equals("P")) {
bottomCategories.add(category);
break;
}
}
categories.removeAll(topCategories);
categories.removeAll(bottomCategories);
Collections.sort(categories, new Comparator<String>() {
@Override
public int compare(String lhs, String rhs) {
return lhs.compareTo(rhs);
}
});
categories.addAll(0, topCategories);
categories.addAll(categories.size(), bottomCategories);
}
And the output is:
Category NAME C Category NAME F Category NAME A Category NAME B Category NAME D Category NAME E Category NAME G Category NAME H Category NAME I Category NAME J Category NAME K Category NAME L Category NAME N Category NAME O Category NAME Q Category NAME R Category NAME M Category NAME P