Reflect collection changes on another

Sébastien Dante Ursini
Tuesday, 18 September 2012 13:36
Written by Sébastien Dante Ursini

Composite Collection

Sometimes you need to reflect the changes you made on a collection in another collection providing a single unified view on a so called composite collection.
To achieve this result you can develop you own observer and replicate the changes on you target collection or you can use Apache Commons Collections .

Depending on you collection type you can use the following classes :

Sample usage

Let's illustrate it using two sets called A and B and an unified collection called unifiedCollection containing the items added in A and B

public class CompositeCollectionTest {

	private final Integer ONE 	= 1;
	private final Integer TWO 	= 2;
	private final Integer THREE	= 3;
	
	@Test
	public void compositeCollection(){
		
		Set<Integer> setA = new HashSet<Integer>(); 
		Set<Integer> setB = new HashSet<Integer>();
				
		CompositeCollection unifiedSet = new CompositeCollection(new Set[]{setA,setB});
		
		setA.add(ONE);
		assertTrue (unifiedSet.contains(ONE));

		setA.add(TWO);
		assertTrue (unifiedSet.contains(TWO));
		
		setB.add(THREE);
		assertTrue (unifiedSet.contains(THREE));
	}
}

Apache Commons Collection is an essential effective and reliable library�for complex collection manipulation.

Tags: unified , let's , illustrate , collection , asserttrue , called , reflect , sets
Sébastien Dante Ursini

Sébastien Dante Ursini

Java/Finance Specialist
17 Years of experience in Java
22 Year in Banking/Finance
Based in Geneva/Switzerland

Comments

0 #1 how to learn java 2012-12-30 05:58
That,we should bare in mind. Reflecting the collection to one another is essential.
Quote

Add comment


Security code
Refresh