[,Hi, ,How,are,you]
我想要移除掉空和null元素,应该怎样修改代码才能达到以下效果:
[Hi,How,are,you]
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
System.out.println(list);
list.removeAll(Arrays.asList("", null));
System.out.println(list);
输出:
[, Hi, null, How]
[Hi, How]
虽然回答已经很晚了,但是您也可以使用 Collections.singleton
:
List<String> list = new ArrayList<String>(Arrays.asList("", "Hi", null, "How"));
// in one line
list.removeAll(Arrays.asList("", null))
// separately
list.removeAll(Collections.singleton(null));
list.removeAll(Collections.singleton(""));
现在我们有Java 8 lambda表达式,可以采用另一种方式来实现此操作。
arrayList.removeIf(item -> item == null || "".equals(item));
arrayList.removeIf(Strings::isNullOrEmpty);
。 - shmoselarrayList.removeIf(StringUtils::isEmpty);
。 - Andrew MairosearrayList.removeIf(StringUtils::isBlank);
。 - Andrew MairoseIf you were asking how to remove the empty strings, you can do it like this (where l
is an ArrayList<String>
) - this removes all null
references and strings of length 0:
Iterator<String> i = l.iterator();
while (i.hasNext())
{
String s = i.next();
if (s == null || s.isEmpty())
{
i.remove();
}
}
Don't confuse an ArrayList
with arrays, an ArrayList
is a dynamic data-structure that resizes according to it's contents. If you use the code above, you don't have to do anything to get the result as you've described it -if your ArrayList
was ["","Hi","","How","are","you"], after removing as above, it's going to be exactly what you need - ["Hi","How","are","you"]
.
However, if you must have a 'sanitized' copy of the original list (while leaving the original as it is) and by 'store it back' you meant 'make a copy', then krmby's code in the other answer will serve you just fine.
null
和空字符串。 - no.good.at.codingnull
和blank
值从array
输入中。public static String[] cleanArray(String[] array) {
return Arrays.stream(array).filter(x -> !StringUtils.isBlank(x)).toArray(String[]::new);
}
filter(StringUtils::isNotBlank)
- AldisStream.of("", "Hi", null, "How", "are", "you")
.filter(t -> !Strings.isNullOrEmpty(t))
.collect(ImmutableList.toImmutableList());
迭代列表,并对要删除的列表元素调用Iterator.remove()
。这是最简单的方法。
重复调用List.remove(Object)
。这也很简单,但性能最差……因为你会反复扫描整个列表。(然而,这可能是一个选项,适用于其迭代器不支持remove
的可变列表……由于某种原因。)
创建一个新列表,遍历旧列表,将要保留的元素添加到新列表中。
如果不能返回新列表,则按照第3种方法操作,然后清除旧列表并使用addAll
将新列表的元素添加回去。
哪种方法最快取决于原始列表的类别、大小和需要删除的元素数量。以下是一些因素:
对于ArrayList
,每个单独的remove
操作都是O(N)
,其中N
是列表大小。使用Iterator.remove()
方法(或ArrayList.remove(element)
方法)从大型ArrayList中删除多个元素是昂贵的。
相比之下,LinkedList
的Iterator.remove
方法是O(1)
。
对于ArrayList
,创建和复制列表是O(N)
的,相对便宜,特别是如果你可以确保目标列表的容量足够大(但不要太大)。
相比之下,创建并复制到LinkedList
也是O(N),但要更昂贵。
所有这些都加起来形成了一个相当复杂的决策树。如果列表很小(比如10个或更少的元素),你可能可以使用上述任何一种方法。如果列表可能很大,你需要权衡列表大小和预期移除数量列表中所有问题。(否则,你可能会得到二次性能。)
public static void listRemove() {
List<String> list = Arrays.asList("", "Hi", "", "How", "are", "you");
List<String> result = new ArrayList<String>();
for (String str : list) {
if (str != null && !str.isEmpty()) {
result.add(str);
}
}
System.out.println(result);
}
str
可能是 null
,所以会抛出一个 java.lang.NullPointerException
。 - no.good.at.codingArrays.asList()
创建的,而且你收到了一个UnsupportedOperationException
,那是因为你无法编辑这样的List
。new LinkedList<String>()
中包装Arrays.asList()
。 List<String> list = new LinkedList<String>(Arrays.asList(split));
以下内容源自这个答案。
Arrays.asList(new String[]{"a", "b", null, "c", " "})
.removeIf(item -> item == null || "".equals(item));
但是你可能会遇到一个java.util.AbstractList.remove
的UnsupportedOperationException
(因为asList
返回的是一个不可调整大小的列表)。
另一种解决方案可能是这样的:
List<String> collect =
Stream.of(new String[]{"a", "b", "c", null, ""})
.filter(item -> item != null && !"".equals(item))
.collect(Collectors.toList());
ArrayList
,而ArrayList
并不是固定大小的。 - Andrew Mairose
java.util.AbstractList.remove()
方法时,我收到了UnsupportedOperationException
异常。 - shkschneiderutil
或awt
库中导入吗? - Lakshya Goyal