简体   繁体   中英

How can sort my hashmap data in ascending order and also descending order

I have a HashMap<String, List<String>> myData I would like to be able to sort my HashMap in ascending order then put it in a variable that I will use to iterate and add to an excel file. I also would like to sort in descending order then get the result in a variable, iterate it and add data to an excel file. My HashMap looks like this: Aug - 19, {"11", "12"} July- 19, {"01", "22"} Jun - 19, {"77", "02"} May - 19, {"99", "42"} The key is the date. And the value is just a list of string. I need to retrieve the variable that contains the sorted data in ascending order and in another variable the sorted data in descending order. Thank you very much for your help.

First convert the key in the map to a more natural format ie Date. Then store them in TreeMap, which is an associative container that stores the keys in sorted order.

Use parse(String) to get Date object and then use format(Date) to regain the string form of it.

public class DateAsTreeMapKey {
    public static void main(String[] args) {
        HashMap<String, List<String>> myData = new HashMap<>();

        String format = "MMM - yy";
        myData.put("Aug - 19", Arrays.asList("11", "12"));
        myData.put("July - 19", Arrays.asList("01", "22")); // try out July also
        myData.put("Jun - 19", Arrays.asList("77", "02"));
        myData.put("May - 19", Arrays.asList("99", "42"));      
        printDataInAscendingOrder(getDataInSortedForm(myData, format), format);
        printDataInDescendingOrder(getDataInSortedForm(myData, format), format);

    }
    public static TreeMap<Date, List<String>> getDataInSortedForm(HashMap<String, List<String>> myData, String format) {
        TreeMap<Date, List<String>> mySortedData = new TreeMap<>();
        for (Map.Entry<String, List<String>> entry : myData.entrySet()) {
            String monthYear = entry.getKey();
            List<String> data = entry.getValue();
            try {
                Date date = new SimpleDateFormat(format, Locale.ENGLISH).parse(monthYear);
                mySortedData.put(date, data);
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
        return mySortedData;
    }
    public static void printDataInAscendingOrder(TreeMap<Date, List<String>> mySortedData, String format) {
        System.out.println("Data in ascending order: ");
        for (Entry<Date, List<String>> entry : mySortedData.entrySet()) {
            System.out.println("Month '" + new SimpleDateFormat(format, Locale.ENGLISH).format(entry.getKey())
                    + "' has data as " + entry.getValue().toString());
        }
    }
    public static void printDataInDescendingOrder(TreeMap<Date, List<String>> mySortedData, String format) {
        System.out.println("Data in descending order: ");
        TreeMap<Date, List<String>> mySortedDataReversed = new TreeMap<>(Collections.reverseOrder());
        mySortedDataReversed.putAll(mySortedData);
        for (Entry<Date, List<String>> entry : mySortedDataReversed.entrySet()) {
            System.out.println("Month '" + new SimpleDateFormat(format, Locale.ENGLISH).format(entry.getKey())
                    + "' has data as " + entry.getValue().toString());
        }
    }
}

prints:

Data in ascending order: 
Month 'May - 19' has data as [99, 42]
Month 'Jun - 19' has data as [77, 02]
Month 'Jul - 19' has data as [01, 22]
Month 'Aug - 19' has data as [11, 12]
Data in descending order: 
Month 'Aug - 19' has data as [11, 12]
Month 'Jul - 19' has data as [01, 22]
Month 'Jun - 19' has data as [77, 02]
Month 'May - 19' has data as [99, 42]

This is a java 1.8+ stream version. It can be more efficient but that might obfuscate the example so I leave that to you. Notice that the only difference between to the sort and reversed order is the .reversed() method.

import org.junit.jupiter.api.Test;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class MapSorter {

    @Test
    public void test() {

        Map<String, List<String>> myData = new HashMap<>();

        myData.put("Aug - 19", Arrays.asList("11", "12"));
        myData.put("July - 19", Arrays.asList("01", "22")); // try out July also
        myData.put("Jun - 19", Arrays.asList("77", "02"));
        myData.put("May - 19", Arrays.asList("99", "42"));

        myData.keySet().stream()
          .map(SortableKey::new)
          .sorted(Comparator.comparingLong(SortableKey::getSortableKey))
          .map(SortableKey::getOriginalKey)
          .forEach(originalKey -> addToExcel(originalKey, myData));
        myData.keySet().stream()
          .map(SortableKey::new)
          .sorted(Comparator.comparingLong(SortableKey::getSortableKey)
                    .reversed())
          .map(SortableKey::getOriginalKey)
          .forEach(originalKey -> addToExcel(originalKey, myData));
    }

    private void addToExcel(String key, Map<String, List<String>> map) {
        System.out.println(key + " = " + map.get(key));
    }

    class SortableKey {

        private String dateStr;
        private long sortableKey;

        SortableKey(String dateStr) {
            this.dateStr = dateStr;
            try {
                sortableKey = new SimpleDateFormat("MMM - yy").parse(dateStr).getTime();
            } catch (ParseException e) {
                // some type of error handling
            }
        }

        long getSortableKey() {
            return sortableKey;
        }

        String getOriginalKey() {
            return dateStr;
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM