0

I need to store the following data in a format so that it can be sorted by the Double value from the lowest value to the highest. I do not know java very well at all.

Index,         Value
"string1",     1.1134
"string2",     2.3469
"string4",     5.2365
"string3",     2.5597
...

I understand I can't use arrays for this. So there are things like ArrayLists, Comparators, Maps, HashMaps and I can't find any similar example to follow with them.

This post (Sort a two dimensional array based on one column) seems close, but I don't understand how it works.

Notes:

  1. I will not know the elements ahead of time, so I wanted to dimension the array at runtime. I hope the design can implement something like "new 2D-ArrayThingy[ExternalArray.size]"
  2. I will obtain all the elements, row by row, in a object based loop. They will always be string followed by double. So understanding how to populate the rows, one at a time is useful. I don't care if the order is string first or not.

Sub-Questions:

  1. How to I store this data per my needs?
  2. How do I sort the data by the doubles values?
  3. How do I output the data (to screen for example)?

TIA!

Community
  • 1
  • 1
usernotdev
  • 117
  • 1
  • 7

2 Answers2

1

You could store them in a TreeMap which will return keys according to their natural order. In this case, you would have the Double as the key and the String as the value.

final Map<Double,String> map = new TreeMap<>();
map.put(1.2, "String2");
map.put(1.0, "String1");
map.put(-1.0, "String0");
for(Double d : map.keySet()) {
    System.out.println(d + " = " + map.get(d));
}

Which outputs:

-1.0 = String0

1.0 = String1

1.2 = String2

Community
  • 1
  • 1
Todd
  • 30,472
  • 11
  • 81
  • 89
  • This does seem to work, but what limitations does this Treemap format have? It looks like it only supports a single "value". So if I end up with a third dimension, the treemap won't work? I'm guessing I could put some array object in the "value" section, but then I would need another method to modify that array (instead of a single method to modify everything). – usernotdev Jan 12 '15 at 13:21
0

You could put them in a TreeMap, as follows:

Map<Double, String> map = new TreeMap<Double, String>();

Then, you can put the objects in through the Map.put() method. The size of the map isn't fixed, so you can edit it at any time you like. Assuming you had two arrays, one of Doubles and one of Strings, that would be paired together, you could:

for (int i = 0; i < doubles.length; ++i)
{
    map.put(doubles[i], string[i]);
}

Then, to print this in order, all you have to do is:

System.out.println(map);

Happy Coding!

puzzler7
  • 16
  • 2