您当前正在为每个元素打印一行(以及它是否小于 0 或大于 0),而不是我将使用 IntStream 和 filter() 它作为所需的元素(并使用 @987654323 收集这些元素@)。喜欢,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
System.out.println("Less than 0: " + IntStream.of(array) //
.filter(x -> x < 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
System.out.println("Greater than 0: " + IntStream.of(array) //
.filter(x -> x > 0).mapToObj(String::valueOf).collect(Collectors.joining(", ")));
输出
Less than 0: -50, -5, -2
Greater than 0: 2, 4, 12, 54, 150
您可以使用一对 StringJoiner(s) 和 for-each 循环和(只是因为)格式化 io 来获得相同的结果。喜欢,
int[] array = { 2, -5, 4, 12, 54, -2, -50, 150 };
Arrays.sort(array);
StringJoiner sjLess = new StringJoiner(", ");
StringJoiner sjGreater = new StringJoiner(", ");
for (int x : array) {
if (x < 0) {
sjLess.add(String.valueOf(x));
} else if (x > 0) {
sjGreater.add(String.valueOf(x));
}
}
System.out.printf("Less than 0: %s%n", sjLess.toString());
System.out.printf("Greater than 0: %s%n", sjGreater.toString());