fuin.org

Small Open Source Java Tools and Libraries

Tracking changes of a map

This is a wrapper for maps that keeps track of all changes made to the map. This means adding, replacing or deleting elements is tracked - not the changes to the objects itself. It's also possible to revert (undo) all changes made to the map.
        
        // Create a standard map
        Map map = new HashMap();
        
        // Add some initial content
        map.put("one", Integer.valueOf(1));
        map.put("two", Integer.valueOf(2));
        map.put("three", Integer.valueOf(3));
        
        // Wrap the map to track changes
        ChangeTrackingMap trackingMap = new ChangeTrackingMap(map);
        
        // Add/change/remove item
        trackingMap.put("four", Integer.valueOf(4));
        trackingMap.put("three", Integer.valueOf(10));
        trackingMap.remove("one");
        
        // Print the status
        // Output: true
        System.out.println("HAS CHANGED:");
        System.out.println(trackingMap.isChanged());
        System.out.println();
        
        // Print the added items
        // Output: "four=4"
        System.out.println("ADDED:");
        printMap(trackingMap.getAdded());
        
        // Print the changed items
        // Output: "three=3"
        System.out.println("CHANGED:");
        printMap(trackingMap.getChanged());
        
        // Print the removed items
        // Output: "one=1"
        System.out.println("REMOVED:");
        printMap(trackingMap.getRemoved());        
        
        // Revert all changes        
        trackingMap.revert();
        
        System.out.println("REVERTED:");
        // Output: "one=1", "two=2", "three=3"
        printMap(trackingMap);        
        
You can find a full example here Internal link outside layout (Package "org.fuin.examples.utils4j").