I have a List<String>
of Units and Chapters for a basic flashcard game. I would like to order them least to greatest (E.G. Chapter 1, Unit 1, Chapter 2 etc...)
Using this code:
String UnitsChaptersString = Utils.GetReviewUnitsChapters().replaceAll(" ", "_");
List<String> UnitsChaptersList = Arrays.asList(UnitsChaptersString.split(","));
for (int i = 0; i < UnitsChaptersList.size(); i++) {
// Order and add to the RecyclerView here...
}
I obtain and loop through a list of units and chapters.
An example String
value returned by Utils.GetReviewUnitsChapters()...
is this:
Chapter_3,Unit_2,Chapter_1
With the string above, the end result should be: Chapter_1,Chapter_3,Unit_2.
For clarity, Unit_2
is greater than both Chapter_1
and Chapter_3
, but Unit_1
is only greater than Chapter_1
.
Important Note: Units 'hold' chapters! Chapters are a subsidiary of Units.
Visual Tree:
Unit_1:
Chapter 1
Chapter 2
Etc...
Unit_2:
Chapter 5
Chapter 6
And so on.
I had this same question for Swift (Eliminate array .sorted errors Swift 5). Note that in Swift, there is a nice .sorted()
function available. Might there be one for Java?
StackOverflow tried to send me to this link, but it wasn't the answer to my question.
I also looked into the List.sort(...)
option, but I ran into the wall of Comparators
and super Strings
, so I was unable to implement that on my own.
Update:
Using one of the suggested methods, I used this code:
List<String> TestList = Arrays.asList("Chapter_1", "Unit_3", "Chapter_42", "Chapter_2");
Collections.sort(TestList);
for (int i = 0; i < TestList.size(); i++) {
Log.i("SortedList", TestList.get(i));
}
And got this:
I/SortedList: Chapter_1
I/SortedList: Chapter_2
I/SortedList: Chapter_42
I/SortedList: Unit_3
Unit_3
should be after Chapter_2
but before Chapter_42
.
In other words, the output needs to be:
I/SortedList: Chapter_1
I/SortedList: Chapter_2
I/SortedList: Unit_3
I/SortedList: Chapter_42
Thank you!