简体   繁体   中英

Remove a String Item from a List of Strings

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".

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.

Use remove :

myStrings.remove("Alpha");

Note that this would only remove the first occurrence of "Alpha" from your list.

boolean remove(Object o)

The above method of ArrayList class will remove the first occurence of Object o from the list.

You can do:

myStrings.remove("Alpha");

It will return true if the ArrayList contained the specified element.

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 .

// 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM