0

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);
                        }
                    }
                }
3
  • 1
    Solution: Don't use a for-each loop. Commented Sep 30, 2016 at 2:10
  • Just wondering as to why would you want to sort the List<Label> and not the List<String> which contains the text of the Labels before creating them? Commented Sep 30, 2016 at 16:24
  • @ItachiUchiha, nice idea. Sorting the strings would probably give a better separation of UI and business logic. Commented Oct 1, 2016 at 11:20

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

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.