我有一张地图,比方说,一周中的一天与降雨量的对比。看上去:
1 -> 5"
2 -> 12"
3 -> 0"
4 -> 0"
5 -> 5"
6 -> 7"
7 -> 12"我想以一种有序的方式组织这件事:
0" -> 3
0" -> 4
5" -> 1
5" -> 5
7" -> 6
12" -> 2
12" -> 7另外,希望将其存储到JSON文件中,并让另一个程序将此JSON读取回来。这两个程序可能没有共享类。因此,如果可能的话,我想尝试使用Java中的标准类来解决这个问题,而不是在每一边编写自定义代码。
这是可能的吗?
我能想到的解决方案之一是写两个数组,第一个数组带有“雨”,第二个数组是平日的索引。
{
"inchRain": [
0, 0, 5, 5, 7, 12, 12
],
"arrIndex": [
3, 4, 1, 5, 6, 2, 7
]
}还有其他人能想到的想法吗?谢谢,
发布于 2016-11-02 08:13:12
我认为你想把你的地图按值排序,而不是按键排序。下面的链接将帮助您建立比较器,它将根据地图的值对地图进行排序。http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java
现在,一旦您的地图准备就绪,您就可以轻松地在单独的数组中获得键和值。
发布于 2016-11-02 07:37:55
您可以轻松地使用Java8流转换您的地图。在您的示例中,您可以将其转换为二维数组,然后将其序列化为Json。在接收端,您可以进行逆翻译。您可以使用任何您想要的JSON库
// sending end
Map<Integer, Integer> data = new TreeMap<>();
data.put(1, 5);
data.put(2, 12);
data.put(3, 0);
data.put(4, 0);
data.put(5, 5);
data.put(6, 7);
data.put(7, 12);
Integer[][] toSend = data.entrySet().stream()
.map(e -> new Integer[] { e.getValue(), e.getKey() })
.sorted((e0, e1) -> e0[0].compareTo(e1[1]))
.toArray(Integer[][]::new);
String fileContent = new Gson().toJson(toSend);
// receiving end
Integer[][] received = new Gson().fromJson(fileContent, Integer[][].class);
Map<Integer, Integer> dataRead = Arrays.stream(received).collect(Collectors.toMap(e -> e[1], e -> e[0]));
assertEquals(data, dataRead);https://stackoverflow.com/questions/40374136
复制相似问题