MULE 4 : REDUCE method : Is there a limit to elements size in Reduce method if the accumulator is an Object?

634 views Asked by At

Scenario : Using Reduce method in Mule 4 to reduce a LIST into three parameters :

  1. Students LIST
  2. Teachers List
  3. Number of Students

Using the below Dataweave Code in Transform Message :

%dw 2.0
output application/java
---
payload reduce((value, acc = { 'totalStudents': 0 as Number,'studentList' : [], 'teachersList' : []}) -> 
    if(
        value.age > 18 and value.age < 25
    ){
        totalStudents : (acc.totalStudents default 0 as Number) + 1,
        studentList : (acc.studentList default [] ) << {
            'studentName' : value.Name ++ " is a Student"
        }
    }else{
        teachersList : acc.teachersList default [] << value.Name ++ " is a Teacher"
    }
)

PROBLEM Statement: The transform message is processed successfully but in the payload I am getting only two values:

  1. payload.totalStudents and
  2. payload.studentList

Can anyone help me to understand why am I not getting payload.teachersList in my result?

4

There are 4 answers

6
Salim Khan On BEST ANSWER

Finally this should get what you are looking for:

%dw 2.0
output application/java
---
payload reduce((value, acc = { 'totalStudents': 0 as Number,'studentList' : [], 'teachersList' : []}) -> 
    if(
        value.age > 18 and value.age < 25
    ){
        totalStudents : (acc.totalStudents default 0 as Number) + 1,
        studentList : (acc.studentList default [] ) << {
            'studentName' : value.Name ++ " is a Student"
        },
        teachersList: acc.teachersList
    }else{
         totalStudents : acc.totalStudents,
         studentList : acc.studentList,
        teachersList : (acc.teachersList default [] ) <<  {'teacherName': value.Name ++ " is a Teacher"}
    }
)```

[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/fcyNf.png
0
Bibek Kr. Bazaz On
%dw 2.0
output application/java
---
payload reduce((value, acc = { 'totalStudents': 0 as Number,'studentList' : [], 'teachersList' : []}) -> 
    if(
        value.age > 18 and value.age < 25
    ){
        totalStudents : (acc.totalStudents default 0 as Number) + 1,
        studentList : (acc.studentList default [] ) << {
            'studentName' : value.Name ++ " is a Student"
        },
        teachersList: acc.teachersList
    }else{
        totalStudents : acc.totalStudents,
        studentList : acc.studentList,
        teachersList : (acc.teachersList default [] ) <<  {'teacherName': value.Name ++ " is a Teacher"}
    }
)

0
Salim Khan On

Hopefully this helps. Since there is an else condition its building the teacher list and is ignoring the student list

enter image description here

0
Salim Khan On

And this as well.. In the input below , the else condition is met with the second element and thus the final output only contains students that are the last 4 entries in the input.

enter image description here