Java中是否存在类似Map的对象,用于存储和访问键/值对,但可以返回键的有序列表和值的有序列表,这样键和值列表的顺序是相同的?
因此,作为代码解释,我正在寻找一些行为类似于我虚构的OrderedMap的东西:
OrderedMap<Integer, String> om = new OrderedMap<>();
om.put(0, "Zero");
om.put(7, "Seven");
String o = om.get(7); // o is "Seven"
List<Integer> keys = om.getKeys();
List<String> values = om.getValues();
for(int i = 0; i < keys.size(); i++)
{
Integer key = keys.get(i);
String value = values.get(i);
Assert(om.get(key) == value);
}
Steffi Keran回答的现代Java版本
public class Solution {
public static void main(String[] args) {
// create a simple hash map and insert some key-value pairs into it
Map<String, Integer> map = new HashMap<>();
map.put("Python", 3);
map.put("C", 0);
map.put("JavaScript", 4);
map.put("C++", 1);
map.put("Golang", 5);
map.put("Java", 2);
// Create a linked list from the above map entries
List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
// sort the linked list using Collections.sort()
list.sort(Comparator.comparing(Map.Entry::getValue));
list.forEach(System.out::println);
}
}
您可以利用NavigableMap接口,该接口可以按升序或降序键顺序访问和遍历。此接口旨在取代SortedMap接口。Navigable map通常根据它的键的自然排序,或者由创建map时提供的Comparator进行排序。
它有三种最有用的实现:TreeMap、ImmutableSortedMap和ConcurrentSkipListMap。
TreeMap例子:
TreeMap<String, Integer> users = new TreeMap<String, Integer>();
users.put("Bob", 1);
users.put("Alice", 2);
users.put("John", 3);
for (String key: users.keySet()) {
System.out.println(key + " (ID = "+ users.get(key) + ")");
}
输出:
Alice (ID = 2)
Bob (ID = 1)
John (ID = 3)
Steffi Keran回答的现代Java版本
public class Solution {
public static void main(String[] args) {
// create a simple hash map and insert some key-value pairs into it
Map<String, Integer> map = new HashMap<>();
map.put("Python", 3);
map.put("C", 0);
map.put("JavaScript", 4);
map.put("C++", 1);
map.put("Golang", 5);
map.put("Java", 2);
// Create a linked list from the above map entries
List<Map.Entry<String, Integer>> list = new LinkedList<>(map.entrySet());
// sort the linked list using Collections.sort()
list.sort(Comparator.comparing(Map.Entry::getValue));
list.forEach(System.out::println);
}
}
我已经使用简单哈希映射,链表和集合排序映射的值。
import java.util.*;
import java.util.Map.*;
public class Solution {
public static void main(String[] args) {
// create a simple hash map and insert some key-value pairs into it
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("Python", 3);
map.put("C", 0);
map.put("JavaScript", 4);
map.put("C++", 1);
map.put("Golang", 5);
map.put("Java", 2);
// Create a linked list from the above map entries
List<Entry<String, Integer>> list = new LinkedList<Entry<String, Integer>>(map.entrySet());
// sort the linked list using Collections.sort()
Collections.sort(list, new Comparator<Entry<String, Integer>>(){
@Override
public int compare(Entry<String, Integer> m1, Entry<String, Integer> m2) {
return m1.getValue().compareTo(m2.getValue());
}
});
for(Entry<String, Integer> value: list) {
System.out.println(value);
}
}
}
输出结果为:
C=0
C++=1
Java=2
Python=3
JavaScript=4
Golang=5