How to sort a treemap key that is a String according to a given set of comparator in Java

Skafkas :

i have a code snippet that is a treemap where the key is the day of week (Monday,Tuesday, etc) and since the treemap automatically sorts the keys, it will only sort it according to the value of alphabets therefore not sorting it according to the order of the day of the week

some example of the already sorted map are like :

"Friday"
"Thursday"
"Tuesday"
"Wednesday"

the code in the impl service are as follow :

@Override
    public ResponseDTO findAllTransactionByUserID(String userId){
        ResponseDTO responseDTO = new ResponseDTO();

        Map<String, Collection<UserHistoryDto>> map = new TreeMap<>();
        List<Transaction> transactions = couponTransactionRepository.findTransactionByUserId(userId);
        User user = userRepository.getOne(userId); //set the object based on ID

        Integer date;
        String day = "";
        responseDTO.setUserPoint(user.getUser_point()); //Get user-point

        for (Transaction trx : transactions) {

            //get the value of days as a map key

            date = trx.getTrans_time().getDayOfWeek().getValue();
            day = trx.getTrans_time().getDayOfWeek().name();
            Collection<UserHistoryDto> col = map.getOrDefault(day, new ArrayList<>());
            col.add(collect(trx));
            map.put(day, col);
        }


        responseDTO.setHistories(map)


        return responseDTO;
    }

the "findAllTransactionByUserID" will do the query already sorted according to the time

the json that came out is:

 {
    "userPoint": 22735,
    "histories": {
        "FRIDAY": [
            {
                "transactionId": "CPT01552",
                "date": 10,
                "day": "FRIDAY",
                "titleName": "Thanos super coupon",
                "pointAffected": 420,
                "transType": "Coupon",
                "month": "MAY"
            }
        ],
        "THURSDAY": [
            {
                "transactionId": "CPT01504",
                "date": 9,
                "day": "THURSDAY",
                "titleName": "Thanos super coupon",
                "pointAffected": 420,
                "transType": "Coupon",
                "month": "MAY"
            },
            {
                "transactionId": "CPT01404",
                "date": 9,
                "day": "THURSDAY",
                "titleName": "Sea Shanties",
                "pointAffected": 475,
                "transType": "Coupon",
                "month": "MAY"
            }
        ],
        "TUESDAY": [
            {
                "transactionId": "CPT01053",
                "date": 7,
                "day": "TUESDAY",
                "titleName": "Thanos super coupon",
                "pointAffected": 420,
                "transType": "Coupon",
                "month": "MAY"
            },
            {
                "transactionId": "CPT00952",
                "date": 7,
                "day": "TUESDAY",
                "titleName": "Sea Shanties",
                "pointAffected": 475,
                "transType": "Coupon",
                "month": "MAY"
            }
        ],
        "WEDNESDAY": [
            {
                "transactionId": "CPT01154",
                "date": 8,
                "day": "WEDNESDAY",
                "titleName": "Sea Shanties",
                "pointAffected": 475,
                "transType": "Coupon",
                "month": "MAY"
            {
                "transactionId": "CPT01102",
                "date": 8,
                "day": "WEDNESDAY",
                "titleName": "Thanos super coupon",
                "pointAffected": 420,
                "transType": "Coupon",
                "month": "MAY"
            }
        ]
    }
}

i would expect the JSON Map where the Wednesday is above the tuesday. something like this:

"Friday"
"Thursday"
"Wednesday"
"Tuesday"

Since comparing the alphabets of the days is not going to work,im trying to find a way to make a comparator where i can compare the value/order of the days so that it can be used as a comparator

i.e : Monday - 1
Tuesday - 2

maybe we can use the variable "Date" on the code snippet as a way to assign the value of each key(or assigning manually if taht works) in the comparator but idk on how to join a comparator with two different data types

im relatively new with java and spring boot and this is my first time asking here in stack overflow, im using java 8 and doesnt know much about lambda expressions... so any critique and help is very helpful thanks!

Eran :

If you change your Map to Map<Integer, Collection<UserHistoryDto>> and change map.put(day, col) to map.put(date, col), you'll get the sorting you want (assuming Monday has the lowest numeric value).

If you must keep the current Map structure, you can pass a Comparator<String> to the constructor of the TreeMap. That Comparator's compare() method will have to map each String value to a corresponding numeric value and compare those values (for example, "Monday" will be mapped to 1, "Tuesday" to 2, and so on...).

Here's one way of creating the Comparator. It requires first creating a Map that maps day Strings into integer values.

Map<String,Integer> dayValues = new HashMap<>();
dayValues.put("Monday",1);
...
dayValues.put("Sunday",7);
Comparator<String> cmpDays = Comparator.comparing(dayValues::get);
...
Map<String, Collection<UserHistoryDto>> map = new TreeMap<>(cmpDays);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=157203&siteId=1