Class CollectionUtil
java.lang.Object
com.ssgllc.fish.service.util.registered.CollectionUtil
-
Nested Class Summary
Nested ClassesModifier and TypeClassDescriptionstatic classstatic classstatic class -
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final BiFunction<Object, Object, Object> static final BiFunction<Object, Object, Object> -
Method Summary
Modifier and TypeMethodDescriptionAdds a key-value pair to an existingMapand returns the updated map.Adds a single value to an existingSetand returns the updated set.addValuesToSet(Set<Object> set, Collection<Object> values) Adds multiple values from a collection to an existingSetand returns the updated set.static booleancontains(Collection<Object> c1, Object c2) Determines if the specified collection contains a particular element.static booleancontainsAny(Collection<Object> c1, Collection<Object> c2) Determines if any elements in the second collection are present in the first collection.
This checks for any overlap between two collections.countOccurrences(List<String> items) Counts the occurrences of each unique string in a list and returns a map with the strings as keys and their counts as values.static CollectionUtil.FluentListCreates a newCollectionUtil.FluentListinstance with an initially empty list.
This allows for fluent-style operations to add elements to the list immediately after creation.static CollectionUtil.FluentMapCreates a newCollectionUtil.FluentMapinstance with an initially empty map.
This allows for fluent-style operations to put entries into the map immediately after creation.static CollectionUtil.FluentSetCreates a newCollectionUtil.FluentSetinstance with an initially empty set.
This allows for fluent-style operations to add elements to the set immediately after creation.Creates an emptyListwith Object type elements.Creates an emptyMapwith String keys and Object values.Creates an emptySetwith Object type elements.static CollectionUtil.FluentListcreateFluentList(Object object) Creates a newCollectionUtil.FluentListinstance initialized with a single object.static CollectionUtil.FluentMapcreateFluentMap(String key, Object object) Creates a newCollectionUtil.FluentMapinstance initialized with a single key-value pair.static CollectionUtil.FluentListcreateListWithObject(List<Object> values, String objectName, Object obj) Creates aCollectionUtil.FluentListby wrapping each value in aCollectionUtil.FluentMapthat includes the value, a zero-based index, and an optional named object reference.
IfobjectNameis provided, the map will include an entry using that name pointing toobj.static CollectionUtil.FluentListcreateListWithRoot(List<Object> values) Creates aCollectionUtil.FluentListwhere each entry is aCollectionUtil.FluentMapcontaining a shared root reference (the input list itself), the current value, and a zero-based index.
Each entry in the returned list is a map with: root – the original input list (values) value – the current element fromvaluesindex – the zero-based position of the element
This is useful for computations that need access to neighboring values (e.g. comparing the current element to the next element) while still producing a list output.Creates aMapwith a single entry using the provided key and value.Creates aSetcontaining a single specified element.createSetFromList(Collection<Object> values) static Collection<Object> excludeNull(Collection<Object> objects) Returns a new collection with all null elements excluded from the given collection.static BooleanExecutes one or more SpEL expressions strictly for their side effects, in left-to-right order, and returnsnullby design so the caller can naturally continue with an Elvis fallback (?:) or ignore the result.
This is primarily a sequencing helper for SpEL, where argument evaluation order is deterministic and can be used to perform assignments/mutations without resorting to dummy ternary expressions.static ObjectexecAndReturn(Object... expressions) Evaluates all provided expressions strictly left-to-right and returns the value of the final expression.
This method is a sequencing helper for SpEL, allowing multiple side-effecting expressions (assignments, mutations, variable population) to be executed in a deterministic order while returning a meaningful final result.
The returned value is always the value of the last expression argument, which may safely depend on state established by earlier expressions.static Collection<Object> flatMap(Collection<Object> objects, String fieldName) Flattens a collection of objects based on a specified field name that represents a nested collection.
This method utilizes reflection to dynamically access getter methods for a specified field, thereby enabling the flattening of nested collections contained within each object.static CollectionUtil.FluentListflatMapWithRoot(Collection<Object> roots, String path) Flattens a collection of root objects by navigating a dot-delimited property path and returns aCollectionUtil.FluentListof maps containing the original root, each resolved leaf value, and the index of that leaf per root.
The path may span multiple levels and collections.Flattens a nested collection or array into a single list of objects.static BiFunction<Object, Object, Object> getBiFunction(String name) static Collection<Object> getDuplicates(Collection<Object> collection1, Collection<Object> collection2) Identifies and returns the common elements between two collections.static StringgetHtmlListFromList(List<String> elements, String listStyle, String itemStyle, String htmlPrepend, String htmlAppend) Converts a list of strings into an HTML unordered list with optional styles and HTML wrappers.static StringgetHtmlTableFromList(List<Map<String, String>> list, List<String> headers, List<String> headerNames, String tableStyle, String thStyle, String tdStyle) Converts a list of maps into an HTML table with optional CSS styles for the table, headers, and cells.static LinkedHashMap<String, Object> getTextAsLinkedMap(String text) Converts a JSON string into aLinkedHashMapmaintaining the order of elements as in the original JSON.static List<LinkedHashMap<String, Object>> getTextAsList(String text) Converts a JSON string into a list ofLinkedHashMaps, preserving the order of elements within each map.static List<LinkedHashMap<String, Object>> getTextAsListFromTemplate(String textTemplateName) Retrieves a list of JSON maps from a named template.getTextAsMap(String text) Converts a JSON string into aMapwith String keys and Object values.getTextAsMapFromTemplate(String textTemplateName) Retrieves a JSON map from a named template.static booleanhasDuplicates(Collection<Object> objects) Determines whether a collection contains duplicates.static booleanisEmpty(Collection<Object> objects) Checks if a collection is empty or null.static booleanisNotEmpty(Object o) Checks if a collection is not empty and not null.static intlength(Collection<Object> objects) Returns the number of elements in a given collection.static Collection<Object> map(Collection<Object> objects, String fieldName) Maps each element in a collection to its specific field value using reflection.static Objectmax(Collection<Object> objects, String fieldName) Finds and returns the maximum element in a collection of objects based on a specified field.static com.ssgllc.fish.service.dto.CasetivityEntityDTOmaxDTO(Collection<com.ssgllc.fish.service.dto.CasetivityEntityDTO> objects, String fieldName) Finds and returns the maximum element in a collection ofbased on the values of a specified field.invalid reference
IdentifierDTOstatic StringmaxValue(Collection<Object> objects, String sortFieldName, String outputFieldName) Retrieves the value of a specified field from the object with the maximum value in another specified field within a collection.Merges one or more maps or collections of maps into a singleMap<String, Object>.
The method recursively traverses the input object, collecting all map entries into a newLinkedHashMap.mergeWithAggregation(Object maps, BiFunction<Object, Object, Object> aggregator) Merges one or more maps or collections of maps into a singleMap<String, Object>, using a provided aggregation function to resolve key collisions.
If the same key appears in multiple maps, the specifiedBiFunctionaggregator is used to combine values.static Objectmin(Collection<Object> objects, String fieldName) Finds and returns the minimum element in a collection of objects based on a specified field.static com.ssgllc.fish.service.dto.CasetivityEntityDTOminDTO(Collection<com.ssgllc.fish.service.dto.CasetivityEntityDTO> objects, String fieldName) Finds and returns the minimum element in a collection ofbased on the values of a specified field.invalid reference
IdentifierDTOstatic StringminValue(Collection<Object> objects, String sortFieldName, String outputFieldName) Retrieves the value of a specified field from the object with the minimum value in another specified field within a collection.recursiveCollectParent(Object object, String parentFieldName) Recursively collects parent objects from a given object, using a specified field name to identify parent relationships, until no further parent is found.
This method is useful for creating a list of parent objects in hierarchical data structures such as organizational charts or nested categories.static Collection<Object> recursiveFlatMap(Collection<Object> objects, String fieldName, boolean includeRoot) Recursively maps and flattens a collection based on a specified field name, optionally including the root level elements.
This method is particularly useful for structures like user roles where each role can inherit other roles, and it's necessary to retrieve all unique roles including inherited ones.static Collection<Object> removeDuplicates(Collection<Object> objects, boolean returnSet) Removes duplicates from a given collection, returning either a Set or a List based on the specified preference.Reverses the order of elements in the provided list.sort(Collection<Object> objects, String fieldName) Sorts a collection of objects based on the values of a specified field.static List<com.ssgllc.fish.service.dto.CasetivityEntityDTO> sortDTO(Collection<com.ssgllc.fish.service.dto.CasetivityEntityDTO> objects, String fieldName) Sorts a collection ofCasetivityEntityDTOobjects based on the values of a specified field.static Numbersum(Collection<? extends Number> objects) Finds and returns the maximum element in a collection of objects based on a specified field.static CollectionUtil.FluentListWraps each item in a list into aCollectionUtil.FluentMapcontaining the item and its zero-based index, returning the results as aCollectionUtil.FluentList.
Each entry in the returned list is a map with: value – the item from the input list index – the zero-based position of the item
-
Field Details
-
SUM_NUMBERS
-
CONCAT_STRINGS
-
-
Method Details
-
length
Returns the number of elements in a given collection.- Parameters:
objects- The collection whose length is to be determined.- Returns:
- The size of the collection, or 0 if the collection is null or empty.
Groovy example:
return collectionUtil.length([1, 2, 3, 4])
Returns:
4
SpEL example:
#length({1, 2, 3, 4})
Returns:
4
-
isEmpty
Checks if a collection is empty or null.- Parameters:
objects- The collection to check.- Returns:
- True if the collection is null or has no elements, false otherwise.
Groovy example:
return collectionUtil.isEmpty([])
Returns:
true
SpEL example:
#isEmpty({})
Returns:
true
-
isNotEmpty
Checks if a collection is not empty and not null.- Parameters:
objects- The collection to check.- Returns:
- True if the collection is not null and contains one or more elements, false otherwise.
Groovy example:
return collectionUtil.isNotEmpty([1, 2, 3])
Returns:
true
SpEL example:
#isNotEmpty({1, 2, 3})
Returns:
true
-
excludeNull
Returns a new collection with all null elements excluded from the given collection.- Parameters:
objects- The collection from which to exclude null elements.- Returns:
- A new collection containing only non-null elements, or null if the input collection is empty or null.
Groovy example:
return collectionUtil.excludeNull([null, 1, null, 2])
Returns:
[1, 2]
SpEL example:
#excludeNull({null, 1, null, 2})
Returns:
[1, 2]
-
flatten
Flattens a nested collection or array into a single list of objects.- Parameters:
objects- The collection or array to flatten.- Returns:
- A list of all elements flattened into one dimension, or null if the input is null.
Groovy example:
return collectionUtil.flatten([[1, 2], [3, [4, 5]]])
Returns:
[1, 2, 3, 4, 5]
SpEL example:
#flatten({{1, 2}, {3, {4, 5}}})
Returns:
[1, 2, 3, 4, 5]
-
merge
Merges one or more maps or collections of maps into a singleMap<String, Object>.
The method recursively traverses the input object, collecting all map entries into a newLinkedHashMap. Supported input types include a single map, an array of maps, or any collection containing maps (or nested collections thereof).- Parameters:
maps- An object that is either aMap, an array of maps, or a collection of maps to merge.- Returns:
- A merged
Map<String, Object>containing all entries from the provided input, ornullif the input isnull.
Groovy example:
def map1 = [a: 1, b: 2]
def map2 = [b: 3, c: 4]
return collectionUtil.merge([map1, map2])
Returns:
[a:1, b:3, c:4]
SpEL example:
#merge({{'a':1, 'b':4}, {'b':2, 'c':3}})
Returns:
{'a':1, 'b':2, 'c':3}
Note: If multiple maps contain the same key, the value from the last map in the order takes precedence.
-
mergeWithAggregation
public static Map<String,Object> mergeWithAggregation(Object maps, BiFunction<Object, Object, Object> aggregator) Merges one or more maps or collections of maps into a singleMap<String, Object>, using a provided aggregation function to resolve key collisions.
If the same key appears in multiple maps, the specifiedBiFunctionaggregator is used to combine values.- Parameters:
maps- An object representing one or more maps—can be aMap, an array of maps, or a collection of maps.aggregator- ABiFunction<Object, Object, Object>used to merge values when duplicate keys are encountered.- Returns:
- A merged
Map<String, Object>with values aggregated for duplicate keys, ornullif input isnull.
Groovy example:
def map1 = [a: 1, b: 4]
def map2 = [b: 2, c: 3]
return collectionUtil.mergeWithAggregation([map1, map2], collectionUtil.getBiFunction("add"))
Returns:
[a:1, b:6, c:3]
SpEL example:
#mergeWithAggregation({{'a':1, 'b':4}, {'b':2, 'c':3}}, #getBiFunction('add'))
Returns:
{'a':1, 'b':6, 'c':3}
Note:- If no aggregator is provided, the last value for each key will override earlier ones.
- Predefined aggregators include:
- "add" – sums numeric values
- "concat" – concatenates string representations
-
getBiFunction
-
map
Maps each element in a collection to its specific field value using reflection.- Parameters:
objects- The collection whose elements are to be mapped based on the field name.fieldName- The name of the field to retrieve value from each object.- Returns:
- A new collection containing the values of the specified field for each object, or null if the input collection is empty or null.
Groovy example:
return collectionUtil.map({new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('dev'), new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('local')}, "environment")
Returns:
["dev", "local"]
SpEL example:
#map({new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('dev'), new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('local')}, "environment")
Returns:
["dev", "local"]Note: this is functionally equivalent to using SpEL projection like:
{new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('dev'), new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('MyNewAppConfig').environment('local')}.![environment]
-
recursiveFlatMap
public static Collection<Object> recursiveFlatMap(Collection<Object> objects, String fieldName, boolean includeRoot) Recursively maps and flattens a collection based on a specified field name, optionally including the root level elements.
This method is particularly useful for structures like user roles where each role can inherit other roles, and it's necessary to retrieve all unique roles including inherited ones.- Parameters:
objects- The collection to process, such as roles associated with a user.fieldName- The field name to map from each object, such as 'parents' to access inherited roles.includeRoot- Specifies whether to include the initial elements of the input collection in the result.- Returns:
- A new collection that contains the flattened results of recursively mapping each element by the specified field name, with duplicates potentially removed if further processed.
Groovy example:
return collectionUtil.recursiveFlatMap(user.roles, "parents", true)
Returns:
[Role(name='Admin'), Role(name='User'), Role(name='Guest')]
SpEL example:
#removeDuplicates(#recursiveFlatMap(user.roles, 'parents', true), true)
Returns:
[Role(name='Admin'), Role(name='User'), Role(name='Guest')]
-
recursiveCollectParent
Recursively collects parent objects from a given object, using a specified field name to identify parent relationships, until no further parent is found.
This method is useful for creating a list of parent objects in hierarchical data structures such as organizational charts or nested categories.- Parameters:
object- The object from which to start the parent collection.parentFieldName- The field name through which the parent object can be identified.- Returns:
- A list of all parent objects collected, ordered from the closest to the most distant parent. Returns an empty list if no parent is found.
Groovy example:
return collectionUtil.recursiveCollectParent(user.roles, "parents")
Returns:
[roleParent1, roleParent2, roleParent3] // Assuming roleParent1 is the direct parent of user.roles, and so on
SpEL example:
#recursiveCollectParent(roles, "parents").![name]
Returns:
["RoleParentClass1", "RoleParentClass2", "RoleParentClass3"] // Simplified output showing class names of parents
-
removeDuplicates
Removes duplicates from a given collection, returning either a Set or a List based on the specified preference.- Parameters:
objects- The collection from which duplicates are to be removed.returnSet- If true, returns a Set, otherwise returns a List.- Returns:
- A new collection containing the unique elements of the original collection, as either a Set or a List based on the `returnSet` parameter.
Groovy example:
return collectionUtil.removeDuplicates([1, 2, 2, 3], true)
Returns:
[1, 2, 3]
SpEL example:
#removeDuplicates({1, 2, 2, 3}, false).size()
Returns:
3
-
hasDuplicates
Determines whether a collection contains duplicates.- Parameters:
objects- The collection to be checked for duplicates.- Returns:
- true if the collection contains duplicates; false otherwise.
Groovy example:
return collectionUtil.hasDuplicates([1, 1, 2, 3])
Returns:
true
SpEL example:
#hasDuplicates({1, 1, 2, 3})
Returns:
true
-
flatMap
Flattens a collection of objects based on a specified field name that represents a nested collection.
This method utilizes reflection to dynamically access getter methods for a specified field, thereby enabling the flattening of nested collections contained within each object.- Parameters:
objects- The collection of objects to be flattened.fieldName- The name of the field that returns a collection, to be flattened into the resulting collection.- Returns:
- A new list containing all elements from the nested collections of each object. Returns null if the input collection is null or empty.
Groovy example:
def users = [new com.ssgllc.fish.service.dto.gen.UserDTO().login('user1').roles([(new com.ssgllc.fish.service.dto.gen.RoleDTO().name('role1'))] as Set), new com.ssgllc.fish.service.dto.gen.UserDTO().login('user2').roles([(new com.ssgllc.fish.service.dto.gen.RoleDTO().name('role1')), (new com.ssgllc.fish.service.dto.gen.RoleDTO().name('role2'))] as Set)] return collectionUtil.flatMap(users, 'roles')
Returns:
The list of roles
SpEL example:
#flatMap({new com.ssgllc.fish.service.dto.gen.UserDTO().login('user1').roles({new com.ssgllc.fish.service.dto.gen.RoleDTO().name('role1')}), new com.ssgllc.fish.service.dto.gen.UserDTO().login('user2').roles({new com.ssgllc.fish.service.dto.gen.RoleDTO().name('role1'), new com.ssgllc.fish.service.dto.gen.RoleDTO().name('role2')})}, "roles").![name]
Returns:
["role1", "role1", "role2"]
-
flatMapWithRoot
public static CollectionUtil.FluentList flatMapWithRoot(Collection<Object> roots, String path) throws ClassNotFoundException, IllegalAccessException, InvocationTargetException Flattens a collection of root objects by navigating a dot-delimited property path and returns aCollectionUtil.FluentListof maps containing the original root, each resolved leaf value, and the index of that leaf per root.
The path may span multiple levels and collections. Any intermediate collection or array encountered while resolving the path is automatically flattened.
Each entry in the returned list is aCollectionUtil.FluentMapwith the following keys:- root – the original root object from the input collection
- value – the resolved leaf object at the end of the path
- index – the zero-based index of the leaf value for that root
- Parameters:
roots- A collection of root objects to traverse (e.g.Organizationinstances).path- A dot-delimited property path to follow from each root (e.g."users.roles").- Returns:
- A
FluentListofFluentMapentries containingroot,value, andindex, ornullif the input collection or path is null/blank.
Groovy example:
return collectionUtil.flatMapWithRoot(organization.children, "users.roles")
Returns:
A FluentList of maps where each map contains: {root: organization, value: role, index: idx}
SpEL example (from Organization entity):
#flatMapWithRoot(#root.children, "users.roles").list.![ { 'orgName': #this.map['root'].name, 'userRole': #this.map['value'].name, 'idx': #this.map['index'] } ]
Returns:
A simplified list of maps containing the organization name, each user role name found via users.roles, and the role index per organization.
Note: The path is resolved using Java getter methods (e.g.getUsers()andgetRoles()for"users.roles"). If any intermediate value is a collection or array, it is automatically flattened. - Throws:
InvocationTargetExceptionIllegalAccessExceptionClassNotFoundException
-
sort
Sorts a collection of objects based on the values of a specified field. The field values are expected to beComparable. This method handles null objects gracefully by placing them at the beginning of the sorted list.- Parameters:
objects- The collection of objects to be sorted.fieldName- The name of the field by which to sort the objects.- Returns:
- A sorted list of objects, or null if the input collection is null or empty. Returns the original list if it contains only one element.
Groovy example:
return collectionUtil.sort([new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('AppB').environment('dev'), new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('AppA').environment('prod')], 'name')
Returns:
[AppConfigDTO(name='AppA', environment='prod'), AppConfigDTO(name='AppB', environment='dev')]
SpEL example:
#sort({new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('AppB').environment('dev'), new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('AppA').environment('prod')}, 'name').![name]
Returns:
["AppA", "AppB"]
-
sortDTO
public static List<com.ssgllc.fish.service.dto.CasetivityEntityDTO> sortDTO(Collection<com.ssgllc.fish.service.dto.CasetivityEntityDTO> objects, String fieldName) Sorts a collection ofCasetivityEntityDTOobjects based on the values of a specified field. The field values are expected to beComparable. This method handles null objects gracefully by placing them at the beginning of the sorted list.- Parameters:
objects- The collection ofCasetivityEntityDTOobjects to be sorted.fieldName- The name of the field by which to sort theCasetivityEntityDTOobjects.- Returns:
- A sorted list of
CasetivityEntityDTOobjects, or null if the input collection is null or empty. Returns the original list if it contains only one element.
Groovy example:
return collectionUtil.sortDTO([new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('EntityB'), new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('EntityA')], 'name')
Returns:
[AppConfigDTO(name='EntityA'), AppConfigDTO(name='EntityB')]
SpEL example:
#sortDTO({new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('EntityB'), new com.ssgllc.fish.service.dto.gen.AppConfigDTO().name('EntityA')}, 'name').![name]
Returns:
["EntityA", "EntityB"]
-
reverse
Reverses the order of elements in the provided list.- Parameters:
objects- The list of objects to be reversed.- Returns:
- The same list of objects after their order has been reversed.
Groovy example:
return collectionUtil.reverse([1, 2, 3, 4])
Returns:
[4, 3, 2, 1]
SpEL example:
#reverse({1, 2, 3, 4}.toArray())
Returns:
[4, 3, 2, 1]
-
sum
Finds and returns the maximum element in a collection of objects based on a specified field. The field values must beComparable. This method handles null objects gracefully by using a comparator that places nulls at the beginning of the order.- Parameters:
objects- The collection of objects from which to find the maximum.fieldName- The name of the field used to determine the maximum value among the objects.- Returns:
- The object with the maximum value in the specified field, or null if the input collection is null or empty. Returns the single element if the collection contains only one.
Groovy example:
return collectionUtil.max([new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)], 'seqNo')
Returns:
IdentifierDTO(prefix='identifier2', seqNo=5)
SpEL example:
#max({new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)}, 'seqNo').seqNo
Returns:
5
-
max
Finds and returns the maximum element in a collection of objects based on a specified field. The field values must beComparable. This method handles null objects gracefully by using a comparator that places nulls at the beginning of the order.- Parameters:
objects- The collection of objects from which to find the maximum.fieldName- The name of the field used to determine the maximum value among the objects.- Returns:
- The object with the maximum value in the specified field, or null if the input collection is null or empty. Returns the single element if the collection contains only one.
Groovy example:
return collectionUtil.max([new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)], 'seqNo')
Returns:
IdentifierDTO(prefix='identifier2', seqNo=5)
SpEL example:
#max({new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)}, 'seqNo').seqNo
Returns:
5
-
maxDTO
public static com.ssgllc.fish.service.dto.CasetivityEntityDTO maxDTO(Collection<com.ssgllc.fish.service.dto.CasetivityEntityDTO> objects, String fieldName) Finds and returns the maximum element in a collection ofbased on the values of a specified field. The field values must beinvalid reference
IdentifierDTOComparable. This method handles null objects gracefully by using a comparator that places nulls at the beginning of the order.- Parameters:
objects- The collection ofIdentifierDTOobjects from which to find the maximum.fieldName- The name of the field used to determine the maximum value among the objects.- Returns:
- The
IdentifierDTOobject with the maximum value in the specified field, or null if the input collection is null or empty. Returns the single element if the collection contains only one.
Groovy example:
return collectionUtil.maxDTO([new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)], 'seqNo')
Returns:
IdentifierDTO(prefix='identifier2', seqNo=5)
SpEL example:
#maxDTO({new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)}, 'seqNo').seqNo
Returns:
5
-
min
Finds and returns the minimum element in a collection of objects based on a specified field. The field values must beComparable. This method handles null objects gracefully by placing them at the end of the order.- Parameters:
objects- The collection of objects from which to find the minimum.fieldName- The name of the field used to determine the minimum value among the objects.- Returns:
- The object with the minimum value in the specified field, or null if the input collection is null or empty. Returns the single element if the collection contains only one.
Groovy example:
return collectionUtil.min([new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)], 'seqNo')
Returns:
IdentifierDTO(prefix='identifier1', seqNo=3)
SpEL example:
#min({new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)}, 'seqNo').seqNo
Returns:
3
-
minDTO
public static com.ssgllc.fish.service.dto.CasetivityEntityDTO minDTO(Collection<com.ssgllc.fish.service.dto.CasetivityEntityDTO> objects, String fieldName) Finds and returns the minimum element in a collection ofbased on the values of a specified field. The field values must beinvalid reference
IdentifierDTOComparable. This method handles null objects gracefully by using a comparator that places nulls first in the order.- Parameters:
objects- The collection ofIdentifierDTOobjects from which to find the minimum.fieldName- The name of the field used to determine the minimum value among the objects.- Returns:
- The
IdentifierDTOobject with the minimum value in the specified field, or null if the input collection is null or empty. Returns the single element if the collection contains only one.
Groovy example:
return collectionUtil.minDTO([new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)], 'seqNo')
Returns:
IdentifierDTO(prefix='identifier1', seqNo=3)
SpEL example:
#minDTO({new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)}, 'seqNo').seqNo
Returns:
3
-
maxValue
public static String maxValue(Collection<Object> objects, String sortFieldName, String outputFieldName) Retrieves the value of a specified field from the object with the maximum value in another specified field within a collection. This method handles null objects by placing them first in the order during sorting.- Parameters:
objects- The collection of objects to evaluate.sortFieldName- The field name used to determine the maximum object.outputFieldName- The field name from which to retrieve the value from the maximum object.- Returns:
- The value of the output field from the maximum object, or null if the collection is null or empty.
Groovy example:
return collectionUtil.maxValue([new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)], 'seqNo', 'prefix')
Returns:
'identifier2'
SpEL example:
#maxValue({new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)}, 'seqNo', 'prefix')
Returns:
'identifier2'
-
minValue
public static String minValue(Collection<Object> objects, String sortFieldName, String outputFieldName) Retrieves the value of a specified field from the object with the minimum value in another specified field within a collection. This method handles null objects by placing them last in the order during sorting.- Parameters:
objects- The collection of objects to evaluate.sortFieldName- The field name used to determine the minimum object.outputFieldName- The field name from which to retrieve the value from the minimum object.- Returns:
- The value of the output field from the minimum object, or null if the collection is null or empty.
Groovy example:
return collectionUtil.minValue([new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)], 'seqNo', 'prefix')
Returns:
'identifier1'
SpEL example:
#minValue({new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier1').seqNo(3), new com.ssgllc.fish.service.dto.gen.IdentifierDTO().prefix('identifier2').seqNo(5)}, 'seqNo', 'prefix')
Returns:
'identifier1'
-
createEmptyMap
Creates an emptyMapwith String keys and Object values.- Returns:
- An empty
HashMap.
Groovy example:
return collectionUtil.createEmptyMap()
Returns:
[:]
SpEL example:
#createEmptyMap()
Returns:
[:]
-
createMap
Creates aMapwith a single entry using the provided key and value.- Parameters:
key- The key to use for the entry.value- The value to associate with the key.- Returns:
- A
HashMapcontaining one key-value pair.
Groovy example:
return collectionUtil.createMap("id", 1)
Returns:
["id": 1]
SpEL example:
#createMap("id", 1)
Returns:
{"id": 1}
-
addToMap
Adds a key-value pair to an existingMapand returns the updated map.- Parameters:
map- The map to which the key-value pair is added.key- The key to add to the map.value- The value to associate with the key.- Returns:
- The updated map with the new key-value pair.
Groovy example:
def existingMap = ["name": "Alice"]
return collectionUtil.addToMap(existingMap, "age", 30)
Returns:
["name": "Alice", "age": 30]
SpEL example:
#addToMap(new java.util.HashMap({'name': 'Alice'}), 'age', 30)Or
#addToMap(#createMap('name', 'Alice'), 'age', 30)
Returns:
{"name": "Alice", "age": 30}
-
createEmptyList
Creates an emptyListwith Object type elements.- Returns:
- An empty
ArrayList.
Groovy example:
return collectionUtil.createEmptyList()
Returns:
[]
SpEL example:
#createEmptyList()
Returns:
[]
-
createEmptySet
Creates an emptySetwith Object type elements.- Returns:
- An empty
HashSet.
Groovy example:
return collectionUtil.createEmptySet()
Returns:
[]
SpEL example:
#createEmptySet()
Returns:
[]
-
createSet
Creates aSetcontaining a single specified element.- Parameters:
value- The value to be added to the set.- Returns:
- A
HashSetcontaining the specified element.
Groovy example:
return collectionUtil.createSet("hello")
Returns:
["hello"]
SpEL example:
#createSet("hello")
Returns:
{"hello"}
-
createSetFromList
- Parameters:
values- The collection of objects to convert into a set.- Returns:
- A
HashSetcontaining the unique elements from the provided collection.
Groovy example:
def listValues = ["apple", "banana", "apple", "orange"]
return collectionUtil.createSetFromList(listValues)
Returns:
["apple", "banana", "orange"]
SpEL example:
#createSetFromList({"apple", "banana", "apple", "orange"})
Returns:
{"apple","banana","orange"}
-
addToSet
Adds a single value to an existingSetand returns the updated set.- Parameters:
set- The set to which the value will be added.value- The value to add to the set.- Returns:
- The updated set with the new element added.
Groovy example:
def existingSet = ["apple", "banana"]
return collectionUtil.addToSet(existingSet, "orange")
Returns:
["apple", "banana", "orange"]
SpEL example:
#addToSet({"apple", "banana"}, "orange")
Returns:
{"apple", "banana", "orange"}
-
addValuesToSet
Adds multiple values from a collection to an existingSetand returns the updated set.- Parameters:
set- The set to which the values are to be added.values- The collection of values to add to the set.- Returns:
- The updated set, or null if the original set is null.
Groovy example:
def existingSet = ["apple", "banana"]
def valuesToAdd = ["banana", "orange", "grape"]
return collectionUtil.addValuesToSet(existingSet, valuesToAdd)
Returns:
["apple", "banana", "orange", "grape"]
SpEL example:
#addValuesToSet({"apple", "banana"}, {"banana", "orange", "grape"})
Returns:
{"apple", "banana", "orange", "grape"}Note: If the original set is null, the method returns null.
-
contains
Determines if the specified collection contains a particular element.- Parameters:
c1- The collection to check.c2- The object to look for in the collection.- Returns:
trueif the collection contains the object;falseotherwise.
Groovy example:
def collection = ["apple", "banana", "orange"]
return collectionUtil.contains(collection, "banana")
Returns:
true
SpEL example:
#contains({"apple", "banana", "orange"}, "banana")
Returns:
true
-
containsAny
Determines if any elements in the second collection are present in the first collection.
This checks for any overlap between two collections.- Parameters:
c1- The first collection to check for elements.c2- The second collection whose elements are to be checked against the first.- Returns:
trueif at least one element from the second collection is found in the first;falseotherwise.
Groovy example:
def fruits = ["apple", "banana", "orange"]
def items = ["banana", "watermelon"]
return collectionUtil.containsAny(fruits, items)
Returns:
true
SpEL example:
#containsAny({"apple", "banana", "orange"}, {"banana", "watermelon"})
Returns:
true
-
createEmptyFluentSet
Creates a newCollectionUtil.FluentSetinstance with an initially empty set.
This allows for fluent-style operations to add elements to the set immediately after creation.- Returns:
- A new instance of
CollectionUtil.FluentSetwith an empty set.
Groovy example:
return collectionUtil.createEmptyFluentSet().add("apple").add("banana").set
Returns:
["apple", "banana"]
SpEL example:
#createEmptyFluentSet().add('apple').add('banana').set
Returns:
["apple", "banana"]
-
withIndex
Wraps each item in a list into aCollectionUtil.FluentMapcontaining the item and its zero-based index, returning the results as aCollectionUtil.FluentList.
Each entry in the returned list is a map with:- value – the item from the input list
- index – the zero-based position of the item
- Parameters:
items- A list of items to index.- Returns:
- A
FluentListof maps containingvalueandindex, ornullifitemsis null.
Groovy example:
return collectionUtil.withIndex(['a','b','c']).list
Returns:
[{"map": {value=a, index=0}}, {"map": {value=b, index=1}}, {"map": {value=c, index=2}}]
SpEL example:
#withIndex({'a','b','c'}).list.![{'i': #this.map['index'], 'v': #this.map['value']}]
Returns:
[{"i":0,"v":"a"},{"i":1,"v":"b"},{"i":2,"v":"c"}]
-
createListWithRoot
Creates aCollectionUtil.FluentListwhere each entry is aCollectionUtil.FluentMapcontaining a shared root reference (the input list itself), the current value, and a zero-based index.
Each entry in the returned list is a map with:- root – the original input list (
values) - value – the current element from
values - index – the zero-based position of the element
This is useful for computations that need access to neighboring values (e.g. comparing the current element to the next element) while still producing a list output.- Parameters:
values- A list of values to wrap.- Returns:
- A
FluentListof maps containingroot,value, andindex.
Groovy example:
def vals = [10.0f, 2.0f, 4.0f]
return collectionUtil.createListWithRoot(vals).list.collect { m ->
def i = m.index
i >= m.root.size()-1 ? null : m.value / m.root[i+1]
}
Returns:
[5.0, 0.5, null]
SpEL example:
#createListWithRoot(#reverse(#sort(labResults,'resultDate')).![resultValue].![#getAfterLast(#this,':')].![T(java.lang.Float).parseFloat(#this)]).getList().![#this.get('index') >= #this.get('root').size()-1 ? null : #this.get('value') / #this.get('root').get(#this.get('index')+1)]
Returns:
[8.0, 0.5, null]
Note:rootis the same list instance for every entry, enabling index-based lookups such asroot.get(index + 1)for "next value" calculations.
- root – the original input list (
-
createListWithObject
public static CollectionUtil.FluentList createListWithObject(List<Object> values, String objectName, Object obj) Creates aCollectionUtil.FluentListby wrapping each value in aCollectionUtil.FluentMapthat includes the value, a zero-based index, and an optional named object reference.
IfobjectNameis provided, the map will include an entry using that name pointing toobj. IfobjectNameis null, no additional object reference is added.
Each entry in the returned list always contains:- value – the current element from
values - index – the zero-based position of the element
- Parameters:
values- A list of values to wrap.objectName- The key under whichobjwill be stored in each map (may be null).obj- The object to associate withobjectName(may be null).- Returns:
- A
FluentListof maps containingvalue,index, and optionally the named object, ornullifvaluesis null.
Groovy example:
return collectionUtil.createListWithObject(['a','b','c'], 'parent', 'hello').list
Returns:
[{"map": {parent="hello", value=a, index=0}}, {"map": {parent="hello", value=b, index=1}}, {"map": {parent="hello", value=c, index=2}}]
SpEL example:
#createListWithObject({'a','b','c'}, 'parent', #this).list.![{'p': #this.map['parent'].id, 'v': #this.map['value'], 'i': #this.map['index']}]
Returns:
[ { "p" : "c0a80142-0139-1e92-819b-00041d653b78", "v" : "a", "i" : 0 }, { "p" : "c0a80142-0139-1e92-819b-00041d653b78", "v" : "b", "i" : 1 }, { "p" : "c0a80142-0139-1e92-819b-00041d653b78", "v" : "c", "i" : 2 } ]
- value – the current element from
-
createFluentList
Creates a newCollectionUtil.FluentListinstance initialized with a single object.- Parameters:
object- The object to add to the new list.- Returns:
- A new instance of
CollectionUtil.FluentListcontaining the provided object.
Groovy example:
return collectionUtil.createFluentList("apple").list
Returns:
["apple"]
SpEL example:
#createFluentList("apple").list
Returns:
["apple"]
-
createEmptyFluentList
Creates a newCollectionUtil.FluentListinstance with an initially empty list.
This allows for fluent-style operations to add elements to the list immediately after creation.- Returns:
- A new instance of
CollectionUtil.FluentListwith an empty list.
Groovy example:
return collectionUtil.createEmptyFluentList().add("apple").add("banana").list
Returns:
["apple", "banana"]
SpEL example:
#createEmptyFluentList().add('apple').add('banana').list
Returns:
["apple", "banana"]
-
createFluentMap
Creates a newCollectionUtil.FluentMapinstance initialized with a single key-value pair. If key is null, does not add key/value.- Parameters:
key- The key for the entry to add to the map.object- The value associated with the key.- Returns:
- A new instance of
CollectionUtil.FluentMapcontaining the provided key-value pair (if key is not null, else an empty FluentMap).
Groovy example:
return collectionUtil.createFluentMap("id", 1).map
Returns:
["id": 1]
SpEL example:
#createFluentMap('id', 1).map
Returns:
{"id": 1}
-
createEmptyFluentMap
Creates a newCollectionUtil.FluentMapinstance with an initially empty map.
This allows for fluent-style operations to put entries into the map immediately after creation.- Returns:
- A new instance of
CollectionUtil.FluentMapwith an empty map.
Groovy example:
return collectionUtil.createEmptyFluentMap().put("name", "Alice").put("age", 30).map
Returns:
["name": "Alice", "age": 30]
SpEL example:
#createEmptyFluentMap().put('name', 'Alice').put('age', 30).map
Returns:
{"name": "Alice", "age": 30}
-
getTextAsMap
public static Map<String,Object> getTextAsMap(String text) throws com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException, IOException Converts a JSON string into aMapwith String keys and Object values.- Parameters:
text- The JSON string to be parsed into a map.- Returns:
- A map representation of the JSON string.
- Throws:
com.fasterxml.jackson.core.JsonParseException- If the input text is not valid JSON.com.fasterxml.jackson.databind.JsonMappingException- If the JSON cannot be converted into a map.IOException- If an input/output exception occurs during parsing.
Groovy example:
return collectionUtil.getTextAsMap('{"key": "value", "number": 42}')
Returns:
["key": "value", "number": 42]
SpEL example:
#getTextAsMap('{"key": "value", "number": 42}')
Returns:
{"key": "value", "number": 42}
-
getTextAsMapFromTemplate
public static Map<String,Object> getTextAsMapFromTemplate(String textTemplateName) throws com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException, IOException Retrieves a JSON map from a named template.- Parameters:
textTemplateName- The name of the text template to be retrieved as a map.- Returns:
- A map representation of the text template.
- Throws:
com.fasterxml.jackson.core.JsonParseException- If the retrieved template is not valid JSON.com.fasterxml.jackson.databind.JsonMappingException- If the JSON cannot be converted into a map.IOException- If an input/output exception occurs during retrieving.
Groovy example:
return collectionUtil.getTextAsMapFromTemplate("configTemplate")
Returns:
["setting1": "value1", "setting2": "value2"]
SpEL example:
#getTextAsMapFromTemplate("configTemplate")
Returns:
{"setting1": "value1", "setting2": "value2"}
-
getTextAsListFromTemplate
public static List<LinkedHashMap<String,Object>> getTextAsListFromTemplate(String textTemplateName) throws com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException, IOException Retrieves a list of JSON maps from a named template.- Parameters:
textTemplateName- The name of the text template to be retrieved as a list of maps.- Returns:
- A list of
LinkedHashMaprepresentations of the text template. - Throws:
com.fasterxml.jackson.core.JsonParseException- If the retrieved template is not valid JSON.com.fasterxml.jackson.databind.JsonMappingException- If the JSON cannot be converted into a list of maps.IOException- If an input/output exception occurs during retrieving.
Groovy example:
return collectionUtil.getTextAsListFromTemplate("listTemplate")
Returns:
[{"item": "one"}, {"item": "two"}]
SpEL example:
#getTextAsListFromTemplate("listTemplate")
Returns:
[{"item": "one"}, {"item": "two"}]
-
getTextAsLinkedMap
public static LinkedHashMap<String,Object> getTextAsLinkedMap(String text) throws com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException, IOException Converts a JSON string into aLinkedHashMapmaintaining the order of elements as in the original JSON.- Parameters:
text- The JSON string to be parsed into a linked map.- Returns:
- A
LinkedHashMaprepresentation of the JSON string, or null if the input text is null. - Throws:
com.fasterxml.jackson.core.JsonParseException- If the input text is not valid JSON.com.fasterxml.jackson.databind.JsonMappingException- If the JSON cannot be converted into a linked map.IOException- If an input/output exception occurs during parsing.
Groovy example:
return collectionUtil.getTextAsLinkedMap('{"key1": "value1", "key2": "value2"}')
Returns:
["key1": "value1", "key2": "value2"]
SpEL example:
#getTextAsLinkedMap('{"key1": "value1", "key2": "value2"}')
Returns:
{"key1": "value1", "key2": "value2"}
-
getTextAsList
public static List<LinkedHashMap<String,Object>> getTextAsList(String text) throws com.fasterxml.jackson.core.JsonParseException, com.fasterxml.jackson.databind.JsonMappingException, IOException Converts a JSON string into a list ofLinkedHashMaps, preserving the order of elements within each map.- Parameters:
text- The JSON string to be parsed into a list of linked maps.- Returns:
- A list of
LinkedHashMaprepresentations of the JSON string, or null if the input text is null. - Throws:
com.fasterxml.jackson.core.JsonParseException- If the input text is not valid JSON.com.fasterxml.jackson.databind.JsonMappingException- If the JSON cannot be converted into a list of linked maps.IOException- If an input/output exception occurs during parsing.
Groovy example:
return collectionUtil.getTextAsList('[{"key1": "value1"}, {"key2": "value2"}]')
Returns:
[{"key1": "value1"}, {"key2": "value2"}]
SpEL example:
#getTextAsList('[{"key1": "value1"}, {"key2": "value2"}]')
Returns:
[{"key1": "value1"}, {"key2": "value2"}]
-
getHtmlListFromList
public static String getHtmlListFromList(List<String> elements, String listStyle, String itemStyle, String htmlPrepend, String htmlAppend) Converts a list of strings into an HTML unordered list with optional styles and HTML wrappers.- Parameters:
elements- The list of strings to convert into list items.listStyle- The CSS style for the list element. If null, a default style will be used.itemStyle- The CSS style for each list item. If null, a default style will be used.htmlPrepend- HTML code to prepend before the list. If null, nothing will be prepended.htmlAppend- HTML code to append after the list. If null, nothing will be appended.- Returns:
- A string containing the HTML unordered list.
Groovy example:
def items = ["Apple", "Banana", "Orange"]
return collectionUtil.getHtmlListFromList(items, "color:blue;", "color:red;", "", "")
Returns:
""- Apple
- Banana
- Orange
SpEL example:
#getHtmlListFromList({"Apple", "Banana", "Orange"}, "color:blue;", "color:red;", "", "")
Returns:
""- Apple
- Banana
- Orange
-
getHtmlTableFromList
public static String getHtmlTableFromList(List<Map<String, String>> list, List<String> headers, List<String> headerNames, String tableStyle, String thStyle, String tdStyle) Converts a list of maps into an HTML table with optional CSS styles for the table, headers, and cells.- Parameters:
list- The list of maps where each map represents a row of data.headers- The list of keys from the maps that identify the columns of the table.headerNames- The list of names to display in the table headers, corresponding to each key in 'headers'.tableStyle- The CSS style for the table element. If null, a default style will be used.thStyle- The CSS style for the table header elements. If null, a default style will be used.tdStyle- The CSS style for the table data elements. If null, a default style will be used.- Returns:
- A string containing the HTML table.
Groovy example:
def data = [ ["name": "John", "age": "30"], ["name": "Jane", "age": "25"] ]
def headers = ["name", "age"]
def headerNames = ["Name", "Age"]
return collectionUtil.getHtmlTableFromList(data, headers, headerNames, "border:1px solid black;", "font-weight:bold;", "text-align:center;")
Returns:
"
"Name Age John 30 Jane 25
SpEL example:
#getHtmlTableFromList({{"name": "John", "age": "30"}, {"name": "Jane", "age": "25"}}, {"name", "age"}, {"Name", "Age"}, "border:1px solid black;", "font-weight:bold;", "text-align:center;")
Returns:
"
"Name Age John 30 Jane 25
-
getDuplicates
public static Collection<Object> getDuplicates(Collection<Object> collection1, Collection<Object> collection2) Identifies and returns the common elements between two collections.- Parameters:
collection1- The first collection to compare.collection2- The second collection to compare.- Returns:
- A collection containing the common elements between the two collections, or null if either collection is null.
Groovy example:
def coll1 = ["apple", "banana", "orange"]
def coll2 = ["banana", "cherry", "apple"]
return collectionUtil.getDuplicates(coll1, coll2)
Returns:
["apple", "banana"]
SpEL example:
#getDuplicates({"apple", "banana", "orange"}.toArray(), {"banana", "cherry", "apple"}.toArray())
Returns:
{"apple", "banana"}
-
countOccurrences
Counts the occurrences of each unique string in a list and returns a map with the strings as keys and their counts as values.- Parameters:
items- A list of strings to count occurrences of.- Returns:
- A map where each key is a unique string from the input list and each value is the count of that string's occurrences.
Groovy example:
return collectionUtil.countOccurrences(['apple', 'banana', 'apple', 'orange'])
Returns:
["apple": 2, "banana": 1, "orange": 1]
SpEL example:
#countOccurrences({'apple', 'banana', 'apple', 'orange'})
Returns:
{"apple": 2, "banana": 1, "orange": 1}
-
exec
Executes one or more SpEL expressions strictly for their side effects, in left-to-right order, and returnsnullby design so the caller can naturally continue with an Elvis fallback (?:) or ignore the result.
This is primarily a sequencing helper for SpEL, where argument evaluation order is deterministic and can be used to perform assignments/mutations without resorting to dummy ternary expressions.- Parameters:
expressions- One or more expressions to evaluate for side effects (evaluated left-to-right).- Returns:
- Always
null.
SpEL example:
#exec(#root.tempVars.put('x', 1), #root.tempVars.put('y', 2)) ?: (#root.tempVars.map['x'] + #root.tempVars.map['y'])
Returns:
3
Note: All arguments are evaluated left-to-right; the return value is always null to enable Elvis chaining.
-
execAndReturn
Evaluates all provided expressions strictly left-to-right and returns the value of the final expression.
This method is a sequencing helper for SpEL, allowing multiple side-effecting expressions (assignments, mutations, variable population) to be executed in a deterministic order while returning a meaningful final result.
The returned value is always the value of the last expression argument, which may safely depend on state established by earlier expressions.- Parameters:
expressions- One or more expressions to evaluate in order.- Returns:
- The value of the last expression, or
nullif no expressions are provided.
SpEL example:
#execAndReturn(#root.tempVars.put('x', 10), #root.tempVars.put('y', 5), #root.tempVars.map['x'] + #root.tempVars.map['y'])
Returns:
15
Note: This method intentionally relies on Java/SpEL left-to-right argument evaluation to guarantee execution order.
-