Philayyy
Philayyy

Reputation: 1927

How to sort an array list of labels based on label text? JavaFX

I am attempting to sort an array list of Label elements with text that has the following format:

"1: Consult with [someone] @14:15"

I am aiming to sort the list via the time variable, specifically the hour between the @ and : . To do this I am sorting through the array list using a for each loop, pulling the text of the label item and extracting the integer between the @ and :

After getting this , I need to run an IF statement to check if the previous Label in the Labels array has a time that is greater than the current, but I am struggling to get the previous array element within this for each loop, is this possible? My code so far:

for (Label label : dailyConsults){

                    String s1 = label.getText();
                    s1 = s1.substring(s1.indexOf("@") +1);
                    int thisConsult = Integer.parseInt(s1.substring(0, s1.indexOf(":")));

                    String s2 = PREVIOUS LABEL IN THIS ARRAY LIST AND GET TEXT
                    s2 = s2.substring(s2.indexOf("@") +1);
                    int previousConsult = Integer.parseInt( s2.substring(0, s2.indexOf(":")));

                    //if previous label time is greater than the current in this loop then move up
                    if(Integer.parseInt(s2) > Integer.parseInt(s1)){

                    while (dailyConsults.indexOf(label) != 0) {
                        int j = dailyConsults.indexOf(label);
                        Collections.swap(dailyConsults, j, j - 1);
                        }
                    }
                }

Upvotes: 0

Views: 1005

Answers (1)

Anonymous
Anonymous

Reputation: 86276

Given that your dailyConsults is a List<Label> you may consider:

    Collections.sort(dailyConsults, Comparator.comparingInt(label -> {
        String s = label.getText();
        s = s.substring(s.indexOf("@") +1);
        return Integer.parseInt(s.substring(0, s.indexOf(":")));
    }));

I am using Java 1.8; in earlier versions it will take a few more lines of code, but you can use the same idea.

Upvotes: 1

Related Questions