从集合中删除长度为1的字符串,排除某些值。

huangapple go评论65阅读模式
英文:

Remove String of length 1 from a Collection excluding some values

问题

我有一个类型为String的ArrayList,其中包含许多单词,有些情况下它们只是单个字母,比如字母 "K"。
我基本上想要删除所有单个字符,除了 "A" 和 "I" 以外的字符。
以下是我尝试过的代码/正则表达式,但没有成功:

//删除所有单个字母
ArrayList<String> newList2 = new ArrayList<String>();
for (String word : words) {
  newList2.add(word.replace("[BCDEFGHJKLMOPQRSTUVWXYZ]", ""));
}
words = newList2;

我是否不应该使用正则表达式?有更好的方法吗?还是我没有正确使用正则表达式?根据我的理解,即使它有效,它也只会用空白替换它,而不是完全删除元素...我的目标是如果存在该元素,则完全删除它,也许可以使用 .remove 方法...不确定如何处理这个问题。(JAVA)

(附言,理想情况下,如果明显存在 "=" 和其他符号,我也想删除它们,但目前我只关心字符。)

英文:

I have an arraylist of type String with many words, and in some cases they are just single letters. Such as the letter "K".
I am essentially trying to remove all single instance characters, EXCEPT "A" and "I".
Here is the code/regex I was trying, to no avail:

//removing all single letters
ArrayList&lt;String&gt; newList2 = new ArrayList&lt;String&gt;();
for(String word : words) {
  newList2.add(word.replace(&quot;[BCDEFGHJKLMOPQRSTUVWXYZ]&quot;, &quot;&quot;));
}
words = newList2;

Should I not use regex? Is there a better method, or is there a way I am not using regex correctly? From my understanding my implementation, if it even worked, would only replace it with an empty spot, not completely remove the element.. my goal is to remove the element entirely if it exists, perhaps by the .remove method... Not sure how to go about this. (JAVA)

(P.S, ideally I would also remove the "=" and other symbols if they are apparent, but characters is my gripe at the moment)

答案1

得分: 10

Sure, here is the translated code part:

不需要使用流API。List#removeIf 在这里足够了:

list.removeIf(s -> s.length() == 1 && !List.of("A", "I").contains(s))

注意:这是一个会修改列表的操作。

英文:

No need to use stream api for it. List#removeIf will suffice here:

list.removeIf(s -&gt; s.length() == 1 &amp;&amp; ! List.of(&quot;A&quot;, &quot;I&quot;).contains(s))

Note: It is a mutative operation.

答案2

得分: 1

A solution with loop:

for (int i = 0; i < newList2.size(); i++) {
    if (newList2.get(i).length() == 1) {
        if (!newList2.get(i).equals("A") || !newList2.get(i).equals("I")) {
            newList2.remove(i);
        }
    }
}
英文:

A solution with loop:

for(int i=0; i &lt; newList2.size(); i++){
    if(newList2.get(i).length() == 1){
        if(!newList2.get(i).equals(&quot;A&quot;) || !newList2.get(i).equals(&quot;I&quot;)){
            newList2.remove(i)
        }
    }
}  

huangapple
  • 本文由 发表于 2020年8月6日 00:50:38
  • 转载请务必保留本文链接:https://go.coder-hub.com/63269879.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定