3

I'm looking to sort an arraylist of strings to make them so all the mondays are at the start of the list and all the fridays are at the end. For example,

days.add("Thursday");
days.add("Monday");
days.add("Friday");
days.add("Wednesday");
days.add("Thursday");
days.add("Thursday");

I would like this to be outputted as follows;

"Monday"
"Wednesday"
"Thursday"
"Thursday"
"Thursday"
"Friday"

I am doing this as I need to graph the results and I'd prefer if the graph was in this order. I was thinking maybe using a mapping to put Monday, 1 : Tuesday, 2 etc and compare that way but I don't know if there is a simpler way. Any help is greatly appreciated Thanks!

RonanD1807
  • 55
  • 1
  • 7
  • If you just need to put index on items you can just put them in a list or an array. Like if you have a list `List.of("orange","black","yellow")` then because of the index of the list you automatically have orange: 0, black: 1, yellow: 2. Instead of a `Map.of("orange",0,"black",1,"yellow",2)` where you would do `get(color)` to get the index, with the list you can do `indexOf(color)`. – Nyamiou The Galeanthrope Mar 30 '20 at 17:05

5 Answers5

3

You can use Enum for days of the week, becouse underneath each of te enums have their own value.

public enum DayOfTheWeek {
    Monday, //default value of 0
    Tuesday, //default value of 1
    Wednesday, //default value of 2
    Thursday, 
    Friday,
    Saturday,
    Sunday
}

Then just make ArrayList of DayOfTheWeek and use Collections.sort().

    ArrayList<DayOfTheWeek> days = new ArrayList<>();
    days.add(DayOfTheWeek.valueOf("Friday"));
    days.add(DayOfTheWeek.valueOf("Monday"));
    days.add(DayOfTheWeek.valueOf("Saturday"));
    days.add(DayOfTheWeek.valueOf("Sunday"));
    Collections.sort(days);
Quazan
  • 79
  • 8
  • That's a great solution but unfortunately these days i'm populating the arraylist with are coming from a database as strings so I don't have the ability to change that to DayOfWeek.day if you know what i'm saying? – RonanD1807 Mar 30 '20 at 15:52
  • 1
    @RonanD1807 Yes you can just use DayOfTheWeek.valueOf("Friday") instead of DayOfTheWeek.Friday – Quazan Mar 30 '20 at 15:55
  • Make that `"Friday".toUpperCase()` when calling `valueOf`. – Basil Bourque Mar 31 '20 at 07:17
1

You can use custom sorting through either implementing Comparable interface method compareTo or Comparator interface compare method
This should help
Sort ArrayList of custom Objects by property

Update : you can make a hashmap like this

HashMap<String , Integer> rank = new HashMap<>();
rank.put("Monday" , 1);
rank.put("Tuesday" , 2);
.
.
and so on..

now just use custom comparator where you sort on the basis of rank.get(currentDay)

Collections.sort(days , new thisway(rank));

then implement the Comparator interface compare method

class thisway implements Comparator<String>{

    private HashMap<String, Integer> rank;

    thisway(HashMap<String , Integer> hashmap){
        this.rank = hashmap;
    }

    @Override
    public int compare(String a , String b){
       if(rank.get(a).intValue() < rank.get(b).intValue()){
           return -1;
       }
       if(rank.get(a).intValue() == rank.get(b).intValue()){
           return 0;
       }
       return 1;
    }
}

I guess this should help.

mss
  • 1,423
  • 2
  • 9
  • 18
1
days.sort(
    Comparator.comparing(day -> DayOfWeek.valueOf(day.toString().toUpperCase()))
);
miken32
  • 42,008
  • 16
  • 111
  • 154
Mark Bug
  • 11
  • 1
  • 1
    Please don't post only code as answer, but also provide an explanation what your code does and how it solves the problem of the question. Answers with an explanation are usually more helpful and of better quality, and are more likely to attract upvotes. – Mark Rotteveel May 29 '22 at 10:28
0

You can define a custom Comparator using the class DayOfWeek in this way:

Comparator<String> comparator = new Comparator<String>() {

    @Override
    public int compare(String day1, String day2) {
        return Integer.compare(DayOfWeek.valueOf(day1.toUpperCase()).getValue(),
                               DayOfWeek.valueOf(day2.toUpperCase()).getValue());
    }
};

After in your code you can call it like below:

List<String> days = new ArrayList<String>();
days.add("Thursday");
days.add("Monday");
days.add("Friday");
days.add("Wednesday");
days.add("Thursday");
days.add("Thursday");
Collections.sort(days, comparator);
System.out.println(days); // will print [Monday, Wednesday, Thursday, Thursday, Thursday, Friday]
dariosicily
  • 4,239
  • 2
  • 11
  • 17
-1

Something like that will do easily:

days.sort(Comparator.comparing(day -> List.of("Monday","Tuesday","Wednesday", "Thursday","Friday","Satursday","Sunday").indexOf(day)));

But make List.of("Monday","Tuesday","Wednesday", "Thursday","Friday","Satursday","Sunday") a constant to avoid recreating it everytime.

  • This needs to be done in two lines. First, `List orderedDays = List.of(…)`, then use orderedDays in the lambda. Creating a brand new, identical List for every single comparison is very inefficient. – VGR Mar 30 '20 at 16:46
  • The list need to be extracted into a constant, having it as a line of code preceding the compare is also inefficient. And I did say so already. – Nyamiou The Galeanthrope Mar 30 '20 at 16:52