Collection Selection
选择是一种强大的表达式语言功能,它允许你通过从源集合中选择其条目来将集合转换为另一个集合。
Selection is a powerful expression language feature that lets you transform a source collection into another collection by selecting from its entries.
选择使用 .?[selectionExpression]
语法。它筛选集合并返回一个包含原始元素子集的新集合。例如,选择允许我们轻松获取塞尔维亚发明家的列表,如下例所示:
Selection uses a syntax of .?[selectionExpression]
. It filters the collection and
returns a new collection that contains a subset of the original elements. For example,
selection lets us easily get a list of Serbian inventors, as the following example shows:
-
Java
-
Kotlin
List<Inventor> list = (List<Inventor>) parser.parseExpression(
"members.?[nationality == 'Serbian']").getValue(societyContext);
val list = parser.parseExpression(
"members.?[nationality == 'Serbian']").getValue(societyContext) as List<Inventor>
选择受支持的数组和任何实现 java.lang.Iterable
或 java.util.Map
的内容。对于数组或 Iterable
,选择表达式针对每个单独元素计算。对于映射,选择表达式针对每个映射项(Java 类型 Map.Entry
的对象)计算。每个映射条目都有其 key
和 value
可作为属性访问以供选择中使用。
Selection is supported for arrays and anything that implements java.lang.Iterable
or
java.util.Map
. For an array or Iterable
, the selection expression is evaluated
against each individual element. Against a map, the selection expression is evaluated
against each map entry (objects of the Java type Map.Entry
). Each map entry has its
key
and value
accessible as properties for use in the selection.
给定存储在名为 #map
的变量中的 Map
,以下表达式返回一个新映射,该映射由原始映射中条目的 value
小于 27 的元素组成:
Given a Map
stored in a variable named #map
, the following expression returns a new
map that consists of those elements of the original map where the entry’s value is less
than 27:
-
Java
-
Kotlin
Map newMap = parser.parseExpression("#map.?[value < 27]").getValue(Map.class);
val newMap = parser.parseExpression("#map.?[value < 27]").getValue() as Map
除了返回所有选定的元素外,您还可以仅检索第一个或最后一个元素。要获取与选择表达式匹配的第一个元素,语法为 .^[selectionExpression]
。要获取与选择表达式匹配的最后一个元素,语法为 .$[selectionExpression]
。
In addition to returning all the selected elements, you can retrieve only the first or
the last element. To obtain the first element matching the selection expression, the
syntax is .^[selectionExpression]
. To obtain the last element matching the selection
expression, the syntax is .$[selectionExpression]
.
Spring 表达式语言还支持集合选择的安全性导航。 The Spring Expression Language also supports safe navigation for collection selection. 有关详细信息,请参阅 Safe Collection Selection and Projection。 See Safe Collection Selection and Projection for details. |