machinery
machinery

Reputation: 6290

How to sort string according to certain substrings?

I have an ArrayList<String>. The entries in the list can be of the following form:

42356_11_1_9345668
562834_12_1_8674852_8
52423_4_2_586284_2
5234_13_9_535567

As you can see the middle part contains the date: xx_y is the day and the month. The other values to the left and right can be of arbitray length. Some Strings have one last additional digit.

I would like to sort the list first according to month (y in xx_y) and then according to day (xx in xx_y). Of course it is possible that the month and day are equal. In this case it should additionally be sorted according to the number following the month (e.g. 8674852 in the second example).

How can this be done? If it is easier with other data structures, this is ok, I'm flexible.

Upvotes: 1

Views: 81

Answers (2)

Puce
Puce

Reputation: 38152

Given the following Entry class:

public class Entry{
   public String getItem(){...}
   public MonthDay getMonthDay(){...}
   public int getNumber(){...}

   public static Entry parseItem(String item){...}
}

You can use the following (untested!):

List<String> sortedItems = items.stream()
    .map(Entry::parseItem)
    .sort(Comparator.comparing(Entry::getMonthDay)
              .thenComparingInt(Entry::getNumber))
    .map(Entry::getItem)
    .collect(Collectors.toList);

Upvotes: 1

Andrew Williamson
Andrew Williamson

Reputation: 8691

If you can put these into other data structures, you definitely should. Parsing a string every time you want to do something with it is painful.

public class Entry implements Comparable<Entry>    // Pick a more descriptive name
{
    int firstNumber;
    int month;
    int day;
    int lastNumber;

    public int compareTo(Entry other)
    {
        int comparison = month - other.month;
        if (comparison == 0)
            comparison = day - other.day;
        return comparison;
    }
}

Make a list of these entries, and then use the Collections methods to sort it:

Collections.sort(list);

Upvotes: 1

Related Questions