Java 从字符串列表中删除字符串项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29407084/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove a String Item from a List of Strings
提问by asdec90
How do I remove a specific string from a List that contains Strings....
如何从包含字符串的列表中删除特定字符串....
As in:
如:
ArrayList<String> myStrings = new ArrayList<>();
myStrings.add("Alpha");
myStrings.add("Beta");
myStrings.add("Gama");
. //The order can be random
.
.
.
Now , I only have the list myStrings and I don't know which String is at which index. But I know, that I want to display all the strings after removing say "Alpha".
现在,我只有 myStrings 列表,我不知道哪个 String 在哪个索引处。但我知道,我想在删除“Alpha”后显示所有字符串。
To Summarize , How can I get the strings from a String array after removing a String that I know that array contains , but don't know its index/position.
总结一下,在删除我知道数组包含但不知道其索引/位置的字符串后,如何从字符串数组中获取字符串。
采纳答案by Eran
Use remove :
使用删除:
myStrings.remove("Alpha");
Note that this would only remove the first occurrence of "Alpha" from your list.
请注意,这只会从您的列表中删除第一次出现的“Alpha”。
回答by Oh Chin Boon
Do you have duplicates in the list of String that you also wish to remove?
您是否也希望删除字符串列表中的重复项?
If so, you can convert the list
of String into a set
of String. Then, you can remove strings from the set
efficiently, convert it back into a map
.
如果是这样,您可以将list
字符串的字符串转换为字符串set
的字符串。然后,您可以set
有效地从字符串中删除字符串,将其转换回map
.
// converting to set will remove duplicates
final Set<String> uniqueStrSet = new HashSet<String>(listOfString);
// remove string from set
uniqueStrSet.remove(strToRemove);
// convert set back to list
list = new ArrayList<String>(uniqueStrSet);
回答by Deepika Rajani
boolean remove(Object o)
The above method of ArrayList class will remove the first occurence of Object ofrom the list.
ArrayList 类的上述方法将从列表中删除第一个出现的对象 o。
You can do:
你可以做:
myStrings.remove("Alpha");
It will return trueif the ArrayList contained the specified element.
如果 ArrayList 包含指定的元素,它将返回true。