我试图从长度为零的LinkedList中删除成员。我试图使代码动态,它从字符串中删除所有空格,但留下的单词分开和顺序。我尝试通过将字符串转换为数组,并在空格处分割它来实现这一点。然后我根据自己的喜好将其转换为LinkedList。
private void sliceItUpFreashness() {
String s = " hello there"; // four spaces at beginning of string
String[] sa = s.split(" ");
LinkedList<String> ll = new LinkedList<>(Arrays.asList(sa));
for (int i = 0; i < ll.size(); i++) {
System.out.println("Size for ll("+i+") == "+ll.get(i).length()); // confirms length of the members is 0
if (ll.get(i).length() == 0) {
ll.remove(i);
}
}
System.out.println("-----");
for (String a : ll) { // this confirms if the zero-length members were removed
System.out.println(a);
}
}
但是上面的代码并没有删除长度为0或null的成员。我能做什么?
我建议您迭代一次数组并直接构建LinkedList
-
String s = " hello there"; // four spaces at beginning of string
String[] sa = s.split(" ");
List<String> ll = new LinkedList<>();
for (String str : sa) {
if (str.length() > 0) { // <-- check for empty string.
ll.add(str);
}
}
另一种解决方案是迭代String本身并跳过split
,
List<String> ll = new LinkedList<>();
StringBuilder sb = new StringBuilder();
for (char ch : s.toCharArray()) { // <-- String toCharArray
if (ch != ' ') {
sb.append(ch); // <-- not a space.
} else {
if (sb.length() > 0) { // <-- add non zero length strings to List
ll.add(sb.toString());
sb.setLength(0);
}
}
}
// Add the last of the buffer
if (sb.length() > 0) {
ll.add(sb.toString());
}
或者使用Collections.singleton("")
String s = " hello there"; // four spaces at beginning of string
String[] sa = s.split(" ");
List<String> list = new ArrayList<String>(Arrays.asList(sa));
list.removeAll(Collections.singleton(""));
代码:
String s = " hello there"; // four spaces at beginning of string
String[] sa = s.split(" ");
LinkedList<String> ll = new LinkedList<>(Arrays.asList(sa));
ll.stream()
.filter( s1 -> !s1.isEmpty())
.map(s1-> s1)
.forEach(System.out::print);
输出:
hello there
hellothere
希望有帮助,如果你需要更多的解释,请告诉我