1. 使用增强for循环和ArrayList:
public String[] removeArrayEmptyTextBackNewArray(String[] strArray) {
List
list = new ArrayList<>(); for (String str : strArray) {
if (str != null && !str.trim().isEmpty()) {
list.add(str.trim());
}
}
return list.toArray(new String);
}
2. 使用Java 8的Stream API:
import java.util.Arrays;
import java.util.stream.Collectors;
public String[] removeArrayEmptyTextBackNewArray(String[] strArray) {
return Arrays.stream(strArray)
.filter(str -> str != null && !str.trim().isEmpty())
.toArray(String[]::new);
}
3. 使用Guava库的`Collections2.filter()`方法(需要导入Guava库):
import com.google.common.collect.Collections2;
public String[] removeArrayEmptyTextBackNewArray(String[] strArray) {
return Collections2.filter(Arrays.asList(strArray), str -> str != null && !str.trim().isEmpty()).toArray(new String);
}
4. 使用循环和ArrayList,并手动删除空值:
public String[] removeArrayEmptyTextBackNewArray(String[] strArray) {
List
list = new ArrayList<>(); for (String str : strArray) {
if (str != null && !str.trim().isEmpty()) {
list.add(str.trim());
}
}
while (list.remove(null));
while (list.remove(""));
return list.toArray(new String);
}
以上方法都可以有效地从数组中移除空值。你可以根据你的具体需求选择合适的方法。需要注意的是,如果你使用的是Java 8或更高版本,推荐使用Stream API,因为它提供了更简洁和函数式的方法来处理集合