I have a set of strings that I'd like to iterate over, and change all of those who equal something, to equal something else:
// Set<String> strings = new HashSet()
for (String str : strings) {
if (str.equals("foo")) {
// how do I change str to equal "bar"?
}
}
I've tried replace() which didn't work. I've also tried removing "str" and adding the desired string, which caused an error. How would I go about doing this?
Two points:
A Set means "only one copy of each". What's the "change all" stuff? Why do you have to iterate over the Set? Why won't this do it?
strings.remove("foo");
strings.add("bar");
Since Set can't have duplicates, what you are trying to do is a bit strange. Why iterate?
if (strings.contains("foo")) {
strings.remove("foo");
strings.add("bar");
}
Make sure that whole block is synchronized properly if that strings set is shared between threads.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With