Reputation: 130
I want just list of id from the Tester object list using SpEL
List<Tester> tests = new ArrayList<Tester>();
tests.add(new Tester(1)); ...
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.setVariable("tests",tests);
System.out.println(tests.stream().map(Tester::getId).collect(Collectors.toList())); // LIKE THIS
System.out.println(parser.parseExpression("#tests what to write here").getValue(context));
Desired Result : [1, 2, 3, 4]
Tester is
public class Tester {
private Integer id;
}
Upvotes: 8
Views: 6187
Reputation: 130
This is a dirty way to do so:
public class ParseCheck {
public static void main(String[] args) throws NoSuchMethodException, SecurityException {
List<Tester> tests = Arrays.asList(new Tester(1),new Tester(2),new Tester(3),new Tester(4),new Tester(1));
ExpressionParser parser = new SpelExpressionParser();
StandardEvaluationContext context = new StandardEvaluationContext();
context.registerFunction("stream", ParseCheck.class.getMethod("stream", String.class));
context.setVariable("tests",tests);
System.out.println(tests.stream().map(Tester::getId).distinct().collect(Collectors.toList()));
System.out.println(parser.parseExpression("#tests.stream().map(#stream('id')).distinct().collect(T(java.util.stream.Collectors).toList())").getValue(context));
}
public static Function<Object, Object> stream(String property) {
ExpressionParser parser = new SpelExpressionParser();
return s -> parser.parseExpression(property).getValue(s);
}
}
Here a function is registered in the context which will return a stream of the property required to be extracted. The property is extracted using SpEL too.
Upvotes: 0
Reputation: 24271
You can use (what they call) Collection Projection (also known as map
in functional programming world):
tests.![id]
Look at the Spring docs for SpEL for reference.
Upvotes: 15