0

I have a map of, lets say, day of week vs the amount of rain, as an example. Looks like:

1 -> 5"
2 -> 12"
3 -> 0"
4 -> 0"
5 -> 5"
6 -> 7"
7 -> 12"

I want to organize this in a sorted way:

0" -> 3
0" -> 4
5" -> 1
5" -> 5
7" -> 6
12" -> 2
12" -> 7

Also, want to store this to a JSON file, and have another program read this JSON back. The 2 programs may not have shared classes. So rather than write custom code on each side, if it is possible, I want to try and solve this problem using the standard classes from Java.

Would this be possible to do?

One solution I can think of of the top of my head is to write 2 arrays, the first one with the " of rain, and the second one which would be the index of the weekday. Thus looking like:

{
 "inchRain": [
  0, 0, 5, 5, 7, 12, 12
 ],
 "arrIndex": [
  3, 4, 1, 5, 6, 2, 7
 ]
}

Any other ideas anyone can think of? Thanks,

Deven
  • 55
  • 1
  • 7

2 Answers2

0

You can easily tranform your map with Java8 streams. In your case you could transform it to a two-dimensional array and then serialize it to Json. On the receiving end you can do the inverse translation. You can use any JSON lib you want

        // 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);
revau.lt
  • 2,674
  • 2
  • 20
  • 31
0

I think you want to sort your map on the Values rather than keys. Below link would help you make the comparator that will sort the map on basis of Values of map. http://stackoverflow.com/questions/109383/sort-a-mapkey-value-by-values-java

Now once you have your map ready, you can then get the key and values in separate array with ease.

Arjun Lajpal
  • 208
  • 1
  • 11