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

I have a set of lines that I would like to iterate over, and change all those who equal something to something else:

// Set<String> strings = new HashSet()
for (String str : strings) {
  if (str.equals("foo")) {
    // how do I change str to equal "bar"?
  }
}

I tried replace () which did not work. I also tried removing the β€œstr” and adding the desired line, which caused an error. How can i do this?

+3
source share
6 answers

Two points:

  • The string is immutable; you cannot β€œchange” the line. You can remove it from the set and replace it with another, but everything changes.
  • A set means "only one copy of each." What is "change everything"? Why do you have to sort out a set? Why won't it be?

    strings.remove ("Foo");
    strings.add ("bar");

+6

Set , , , . ?

if (strings.contains("foo")) {
  strings.remove("foo");
  strings.add("bar");
}

, , strings .

+2

iterationg .

:

Set<String> strings = new HashSet();
strings.add("foo");
strings.add("baz");

Set<String> stringsNew = new HashSet();

for (String str : strings) {
    if (str.equals("foo")) {
    stringsNew.add("bar");
    } else {
    stringsNew.add(str);
    }
}

System.out.println(stringsNew);
+1

HashSet , ConcurrentModificationException. , "foo", "bar" -

0

, . , "" - , , , "" .

0
// Set<String> s = new HashSet();

     for (String str : s) {
                if (str.equals("foo")) {
                    s.remove(str);
                    s.add("bar");
                }
            }
0

All Articles