在 Java 中按键对 Map 值进行排序
要按键对 Map 中的值进行排序,请考虑使用 TreeMap 或自定义 SortedSet比较器。
使用TreeMap
使用SortedSet
代码示例:
import java.util.SortedSet; import java.util.TreeMap; import java.util.TreeSet; public class MapSortByKey { // Using TreeMap public static void sortByTreeMap() { Map<String, String> map = new TreeMap<>(); map.put("question1", "1"); map.put("question9", "1"); map.put("question2", "4"); map.put("question5", "2"); // Iterate through the sorted map StringBuilder questionString = new StringBuilder(); StringBuilder answerString = new StringBuilder(); for (Map.Entry<String, String> entry : map.entrySet()) { questionString.append(entry.getKey() + ","); answerString.append(entry.getValue() + ","); } // Remove the trailing commas questionString.setLength(questionString.length() - 1); answerString.setLength(answerString.length() - 1); System.out.println("Questions: " + questionString); System.out.println("Answers: " + answerString); } // Using SortedSet public static void sortBySortedSet() { Map<String, String> map = new HashMap<>(); map.put("question1", "1"); map.put("question9", "1"); map.put("question2", "4"); map.put("question5", "2"); // Create a sorted set of the keys SortedSet<String> keys = new TreeSet<>(map.keySet()); // Iterate through the sorted keys StringBuilder questionString = new StringBuilder(); StringBuilder answerString = new StringBuilder(); for (String key : keys) { String value = map.get(key); questionString.append(key + ","); answerString.append(value + ","); } // Remove the trailing commas questionString.setLength(questionString.length() - 1); answerString.setLength(answerString.length() - 1); System.out.println("Questions: " + questionString); System.out.println("Answers: " + answerString); } public static void main(String[] args) { sortByTreeMap(); sortBySortedSet(); } }
以上是如何在 Java 中按键对 Map 的值进行排序?的详细内容。更多信息请关注PHP中文网其他相关文章!