4

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?

6 Answers 6

7

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

Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

1

You should not change the set while iterationg over it.

Better try this:

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

Comments

0

If you change your HashSet in the middle of iteration, you get ConcurrentModificationException. That means, you have to remove "foo" first, and then add "bar" - outside iterator

Comments

0

A set is a collection that contains no duplicate objects. Therefore if you wish to 'replace' an object in a set with something else, you can simply remove it first, and then add the string you wish to 'replace' it with.

Comments

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

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

1 Comment

` s.add("b"); s.add("s"); s.add("x"); s.add("d"); System.out.println(s); for (String str : s) { System.out.println(str); if (str.equals("x")) { s.remove(str); s.add("asdf"); } } System.out.println(s); ` i have tried this and not getting exception

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.