в массиве array null нужно переместить в конец массива
public class Defragment {
public static String[] compress(String[] array) {
for (int index = 0; index < array.length; index++) {
if (array[index] == null) {
int point = index;
for (int i = 0; i < array.length; i++) {
if (array[i] != null) {
int notNullIndex = i;
i = point;
point = notNullIndex;
}
}
}
System.out.print(array[index] + " ");
}
return array;
}
public static void main(String[] args) {
String[] input = {"I", null, "wanna", null, "be", null, "compressed"};
String[] compressed = compress(input);
System.out.println();
for (int index = 0; index < compressed.length; index++) {
System.out.print(compressed[index] + " ");
}
}
}
Ответы (3 шт):
Автор решения: Aziz Umarov
→ Ссылка
так посмотрите
public static void main(String[] args) {
String[] input = {"I", null, "wanna", null, "be", null, "compressed"};
Stream.of(input)
.sorted((a, b) -> a == null ? 1 : -1)
.forEach(System.out::println);
}
А ваш код я бы изменил так. Чтоб не копировать ответ с низу
public static String[] compress(String[] array) {
for (int index = 0; index < array.length; index++) {
for (int i = 0; i < array.length - index - 1; i++) {
if (array[i] == null) {
String notNullIndex = array[i + 1];
array[i + 1] = array[i];
array[i] = notNullIndex;
}
}
System.out.print(array[index] + " ");
}
return array;
}
public static void main(String[] args) {
String[] input = {"I", null, "wanna", null, "be", null, "compressed"};
String[] compressed = compress(input);
System.out.println();
for (int index = 0; index < compressed.length; index++) {
System.out.println(compressed[index] + " ");
}
}
Автор решения: Дмитрий
→ Ссылка
Без стримов будет так:
public static String[] compress(String[] array) {
String[] result = new String[array.length];
int i = 0;
for (String value : array) {
if (value != null) result[i++] = value;
}
return result;
}
Со стримами, помимо уже указанного способа с сортировкой, можно таким способом :
public static String[] compress(String[] array) {
return Stream.of(array)
.filter(Objects::nonNull)
.toArray(v -> new String[array.length]);
}
Автор решения: Vladyslav
→ Ссылка
String [] result = new String[array.length];
int count = 0;
for (int i = 0; i < array.length; i++) {
if (array[i] != null){
result[count] = array[i];
count++;
}
}
for (int i = 0; i < array.length; i++) {
array[i] = result[i];
}
Как вариант можно просто записать все данные из одного массива в другой ,а потом залить их обратно и все отсортировано