[英]How do I store, sort and print a 2D “array” of strings and doubles in Java?
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. 我需要以一种格式存储以下数据,以便可以按从最低值到最高值的Double值对其进行排序。 I do not know java very well at all.
我一点都不了解Java。
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.
因此,存在诸如ArrayLists,Comparators,Maps,HashMaps之类的东西,我找不到任何类似的示例可以跟随它们。
This post ( Sort a two dimensional array based on one column ) seems close, but I don't understand how it works. 这篇文章( 基于一列对二维数组进行排序 )似乎很接近,但是我不知道它是如何工作的。
Notes: 笔记:
Sub-Questions: 次要问题:
TIA! TIA!
You could store them in a TreeMap
which will return keys according to their natural order. 您可以将它们存储在
TreeMap
, TreeMap
将根据其自然顺序返回键。 In this case, you would have the Double as the key and the String as the value. 在这种情况下,您将把Double作为键,将String作为值。
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 =字符串0
1.0 = String1
1.0 =字符串1
1.2 = String2
1.2 =字符串2
You could put them in a TreeMap
, as follows: 您可以将它们放在
TreeMap
,如下所示:
Map<Double, String> map = new TreeMap<Double, String>();
Then, you can put the objects in through the Map.put()
method. 然后,可以通过
Map.put()
方法放入对象。 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:
假设您有两个数组,一个是Doubles,另一个是Strings,可以配对在一起,则可以:
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! 编码愉快!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.