Search code examples
javaspringcollectionsspring-el

Update property in collection with spring expression language (SpEL)


Is it possible with spring expression language to extract a collection and at the same time modify a property on each object in the collection? In my example I have a list of users whose name is too lang and I would like to limit the length of the names before they are displayed in a page (so not update the original list). This code is used in a controller which is requested via ajax and the list of users is returned as a json array.

ExpressionParser parser = new SpelExpressionParser();
EvaluationContext context = new StandardEvaluationContext(rankedUsers);
List<User> longNamedUsers = (List<User>) parser.parseExpression("?[name.length() > 20]").getValue(context);

EvaluationContext newContext = new StandardEvaluationContext(longNamedUsers);
// the below does not work but throws an exception
//parser.parseExpression("?[name]").setValue(newContext, "test");

Solution

  • You have some possibilities, matters what you want to achieve. To get all names, and those who are longer then a certain size shorten, you can do it this way:

    List<User> lu = new ArrayList<User>();
    lu.add(new User("Short user name"));
    lu.add(new User("Very long user name which should be shortend"));
    
    ExpressionParser parser = new SpelExpressionParser();
    EvaluationContext context = new StandardEvaluationContext(lu);
    
    List<String> names = (List<String>)parser.parseExpression("![name.length() > 20 ? name.substring(0,20) : name]").getValue(context);
    
    for (String name : names) {
        System.out.println("Name: " + name);
    }