Home > OS >  How to split a HashMap in Apache Camel?
How to split a HashMap in Apache Camel?

Time:08-04

I have a Map<String, List<String>> with size 14. I need to split the map so that I can get 14 maps of 1 size. I've tried the following code, but the split is not working: the size after the split is still 14.

from("direct:receive-the-list")
    .errorHandler(defaultErrorHandler())
    .bean(new ListToMapTransformer()) // aggregate list of strings into a Map of strings based on some prefix
    .log("Size of the body BEFORE SPLIT: ${body.size}");    
    .split(body())
    .log("Size of the body AFTER SPLIT: ${body.size}");

Does anyone know how I can get it to work?

CodePudding user response:

I dont understand your question bu I think this code examples solves your problem . split behaviour in Map is Map.Entry . and this returns Node.class and you can get this value with .value

        from("timer:test?repeatCount=1")
            .process(e -> {
                Map<String, List<String>> map = new HashMap<>();
                map.put("name", List.of("name", "name1","namo"));
                map.put("surname", List.of("surname"));
                map.put("age", List.of("age", "age1"));
                e.getIn().setBody(map);
            })
            .split(body())
            .setBody(simple("${body.value}"))
            .log("${body.class} ${body.size} ${body}");

output

:class java.util.ImmutableCollections$List12 1 surname
:class java.util.ImmutableCollections$ListN 3 name,name1,namo
:class java.util.ImmutableCollections$List12 2 age,age1

or more complicated example. u can split every list field to a body

from("timer:test?repeatCount=1")
        .log("its works")
        .process(e -> {
            Map<String, List<String>> map = new HashMap<>();
            map.put("name", List.of("name", "name1"));
            map.put("surname", List.of("surname", "surname1"));
            map.put("age", List.of("age", "age1"));
            e.getIn().setBody(map);
        })
        .split(body(), new GroupedBodyAggregationStrategy())
        .setBody(simple("${body.value}"))
        .split(body(), new GroupedBodyAggregationStrategy())
        .log("${body}");

CodePudding user response:

Sounds like maybe you just want iterate on the map entries:

.split(simple("${body.entrySet()}"))
    .log("${body.key}") // key is a String
    .log("${body.value}") // value is List<String> 
  • Related