Apache Camel – Index of Map or List from camel routes

From inside a camel route we can retrieve the value by using its index easily.

To retrieve an item from a list by using index, use below code which will reads the list object in the exchange body and retrieves the value in position 2.

simple("${body[2].name}")

To retrieve an item from a map having String as key, use below code:

simple("${body[foo].empName}")

Here in the above example the key used is foo. Suppose my key contains spaces, like foo bar. In those cases you needs to enclose those keys with quotes.

For example:

simple("${body['foo bar'].empName}")

In case there is no keyword foo in the map, code will throw NullPointerException. In those cases use null safe operator.

simple("${body[foo]?.empName}")

Camel also provides a keyword last to retrieve the last item of the collection.

simple("${body[last]?.empName}")

 

Leave a Reply

Your email address will not be published. Required fields are marked *