简体   繁体   English

如何将我的哈希图数据按升序和降序排序

[英]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. 我有一个HashMap<String, List<String>> myData我希望能够以升序对我的HashMap进行排序,然后将其放入一个变量中,该变量将用于迭代并添加到excel文件中。 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. 我还想按降序排序,然后将结果存入一个变量,对其进行迭代,然后将数据添加到excel文件中。 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. 我的HashMap如下所示: Aug - 19, {"11", "12"} July- 19, {"01", "22"} Jun - 19, {"77", "02"} May - 19, {"99", "42"}关键是日期。 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. 然后将它们存储在TreeMap中,TreeMap是一个按顺序存储键的关联容器。

Use parse(String) to get Date object and then use format(Date) to regain the string form of it. 使用parse(String)获取Date对象,然后使用format(Date)重新获得它的字符串形式。

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. 这是Java 1.8+流版本。 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. 请注意,排序和倒序之间的唯一区别是.reversed()方法。

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;
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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