Iterating through an arraylist of sets

Christian Carrión :

I'm currently trying to iterate through an arraylist of sets that contain strings. It looks like this:

ArrayList<Set<String>> e = new ArrayList<Set<String>>(Size);

    for(int i = 0; i < e.size(); i++) {
        for(Object obj: e) {
            System.out.println(e);
        }
    }

I'm trying to access and modify the strings inside the set (Printed beforehand to see if it worked), but I can't find a way to get to them. Any ideas?

tquadrat :

You cannot modify a String; if you want to change one of the Strings in the Sets, you have to remove it and to add the new one.

Regarding the (simple) iteration:

for( var set : e )
{
  for( var string : set )
  {
     out.println( string );
  }
}

If you want to change the contents of your data structure:

for( var set : e )
{
  Set<String> newStrings = new HashSet<>();
  for( var i = set.iterator(); i.hasNext(); )
  {
    var string = i.next();
    if( isInvalid( string ) )
    { 
      i.remove();
      newStrings.add( calculateNewString( string ) );
    } 
  }
  set.addAll( newStrings );
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=194955&siteId=1