gw.lang.enhancements.CoreSetEnhancement.gsx Maven / Gradle / Ivy
package gw.lang.enhancements
uses java.lang.*
uses java.util.Set
uses java.util.HashSet
uses java.util.Collections
uses java.util.HashMap
uses java.util.Map
/*
* Copyright 2014 Guidewire Software, Inc.
*/
enhancement CoreSetEnhancement : Set
{
/**
* Returns this Set cast to a Set, checking each element in the
* list to ensure the cast is legal.
*/
reified function cast( type : Type ) : Set {
for( elt in this ) {
if( not type.Type.isAssignableFrom( typeof elt ) ) {
throw new IllegalArgumentException( "The element ${elt} is not of type ${type.Type.Name}" )
}
}
return this as Set
}
/**
* Partitions each element into a Map where the keys are the value produce by the mapper block and the
* values lists of elements of the Collection that map to that value.
*/
reified function partition( partitioner(elt : T):Q ) : Map> {
var returnMap = new HashMap>()
var autoMap = returnMap.toAutoMap( \ q -> new HashSet() )
for( elt in this )
{
autoMap[ partitioner( elt ) ].add( elt )
}
return returnMap
}
/**
* Returns the powerset of this set. That is, it returns all possible subsets
* of this set. An exception will be thrown if this set is larger than 10, to avoid
* very long-running calculations
*/
reified function powerSet() : Set> {
if( this.size() > 10 ) {
throw "You cannot call powerSet() on a set that is larger than size 10. It will kill the CPU."
} else {
var returnSet = new HashSet>(){ new HashSet(){} }
for( t in this ) {
var temp = new HashSet>()
for( h in returnSet ) {
var copy = h.clone() as HashSet
copy.add( t )
temp.add( copy )
}
returnSet.addAll( temp )
}
return returnSet
}
}
/**
* Returns a read-only version of this set
*/
function freeze() : Set {
return Collections.unmodifiableSet( this )
}
/**
* Returns a copy of this set
*/
function copy() : Set {
return new HashSet(this)
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy