Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change a string in Set<String> during foreach iteration?

Tags:

java

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?

like image 211
tsiki Avatar asked Oct 21 '25 04:10

tsiki


2 Answers

Two points:

  1. String is immutable; you can't "change" a String. You can remove one from the Set and replace it with another, but that's all that changing.
  2. 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");

like image 136
duffymo Avatar answered Oct 23 '25 18:10

duffymo


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.

like image 35
Mat Avatar answered Oct 23 '25 18:10

Mat