我正在做一个学校项目,我需要按花费(降序)打印数组。问题是我通过将5个数组连接成一个并且必须在for循环中收集信息而在其中得到空值,因此我必须在我的代码顶部声明该数组。
所以我的代码是这样的:
⇩
Entry | Amount | Category | Payment | Date
String array[][]={ {"5", "22,2", "car payment", "visa", "21/04/2016"},
{"1", "44,4", "shop", "cash", "16/02/2017"},
{"2", "33,1", "shop", "cash", "15/01/2020"},
{"3", "17,3", "gym", "visa", "10/01/2016"},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null}, };
所以我尝试使用Arrays.sort()
使用Comparator
,但我似乎无法把它弄好,因为我得到了这些空值我总是得到java.lang.NullPointerException
。
我试过的是:
Arrays.sort(array, (String[] o1, String[] o2) -> Float.compare(Float.parseFloat(o2[1]),
Float.parseFloat(o1[1])));
我想要的是:
{"1", "44,4", "shop", "cash", "16/02/2017"},
{"2", "33,1", "shop", "cash", "15/01/2020"},
{"5", "22,2", "car payment", "visa", "21/04/2016"},
{"3", "17,3", "gym", "visa", "10/01/2016"}};
任何帮助都会非常感激。谢谢!
答案 0 :(得分:1)
我相信以下代码运作良好:
public class StringArraySorter {
public static void main(String[] args) {
String array[][]={ {"5", "22,2", "car payment", "visa", "21/04/2016"},
{"1", "44,4", "shop", "cash", "16/02/2017"},
{"2", "33,1", "shop", "cash", "15/01/2020"},
{"3", "17,3", "gym", "visa", "10/01/2016"},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
{null, null, null, null, null},
};
Arrays.sort(array, new Comparator<String[]>() {
@Override
public int compare(String[] o1, String[] o2) {
String a1 = o1[1]; // amount field
String a2 = o2[1]; // amount field
if (a1 != null && a2 != null) {
a1 = a1.replace(',', '.');
a2 = a2.replace(',', '.');
return Float.compare(Float.parseFloat(a2), Float.parseFloat(a1));
}
return 1; // non-null value for amount takes precedence, whatever that may be
}
});
System.out.println(Arrays.deepToString(array));
}
}
它打印(修改为插入换行符),符合您的要求:
[[1, 44,4, shop, cash, 16/02/2017],
[2, 33,1, shop, cash, 15/01/2020],
[5, 22,2, car payment, visa, 21/04/2016],
[3, 17,3, gym, visa, 10/01/2016],
[null, null, null, null, null],
[null, null, null, null, null],
[null, null, null, null, null],
[null, null, null, null, null]]
现在,您可以始终修剪您的输入数组,以便在发送数组之前删除具有某些关键字段null
(或以其他方式无效)的记录(字符串数组)到Arrays.sort
方法。使用Java 8构造(但可以说有点神秘)的初步尝试是:
Arrays.stream(array).filter(a -> a[2] != null)
.sorted((o1, o2) -> Float.compare(Float.parseFloat(o1[1].replace(',', '.')), Float.parseFloat(o1[1].replace(',', '.'))))
.forEach(a -> System.out.println("{" + Arrays.stream(a).map(s -> "\"" + s + "\"").collect(Collectors.joining(", ")) +
"}"));
打印:
{"1", "44,4", "shop", "cash", "16/02/2017"}
{"2", "33,1", "shop", "cash", "15/01/2020"}
{"5", "22,2", "car payment", "visa", "21/04/2016"}
{"3", "17,3", "gym", "visa", "10/01/2016"}