fork download
  1. /* package whatever; // don't place package name! */
  2.  
  3. import java.util.*;
  4. import java.lang.*;
  5. import java.io.*;
  6.  
  7. /* Name of the class has to be "Main" only if the class is public. */
  8. class Ideone
  9. {
  10. public static void main (String[] args) throws java.lang.Exception
  11. {
  12. List< Map< String, String > > listOfMapsOfNames = new ArrayList<>() ;
  13. Map< String, String > mapOfNames = new HashMap<>() ;
  14.  
  15. mapOfNames.put( "name", "John" );
  16. mapOfNames.put( "lastname", "McKoy" );
  17. listOfMapsOfNames.add( Map.copyOf( mapOfNames ) ); // Make an unmodifiable copy of map to be added to list.
  18.  
  19. System.out.println( "map before clear: " + mapOfNames );
  20. mapOfNames.clear();
  21. System.out.println( "map after clear: " + mapOfNames );
  22.  
  23. mapOfNames.put( "name", "Tom" );
  24. mapOfNames.put( "lastname" , "Red" );
  25. listOfMapsOfNames.add( Map.copyOf( mapOfNames ) ); // Make an unmodifiable copy of map to be added to list.
  26.  
  27. System.out.println( "map after 2nd add: " + mapOfNames );
  28. System.out.println( "list at the end: " + listOfMapsOfNames );
  29. }
  30. }
Success #stdin #stdout 0.09s 53900KB
stdin
Standard input is empty
stdout
map before clear: {name=John, lastname=McKoy}
map after clear: {}
map after 2nd add: {name=Tom, lastname=Red}
list at the end: [{name=John, lastname=McKoy}, {name=Tom, lastname=Red}]