Search code examples
javalambda

java 8 : Mapper function with dynamic method


I am trying to make a mapping and get some descriptions. The problem I have is that I don't know how to make mapper function with dynamic parameters.

My code is the following:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class TEST{

     public static String getDesc(String domain, String code){
         String ret = "";
         
         switch(domain){
             case "AAA" :    
                 if(code.equals("0")){
                     ret = "AAA_Descr_0";
                 }else if(code.equals("1")){
                     ret = "AAA_Descr_1";
                 }
             break;

             case "BBB" :    
                 if(code.equals("0")){
                     ret = "BBB_Descr_0";
                 }else if(code.equals("1")){
                     ret = "BBB_Descr_1";
                 }
             break;
         }
         
         return ret;
     }
     
     public static void main(String []args){
       List<String> cities = Arrays.asList("AAA","AAA","BBB", "BBB");
       List<String> codes = Arrays.asList("0","1","0","1");
       List<String> descs = codes.stream()
        .map(code -> getDesc( "AAA", code))
        .distinct()
        .filter(code -> code != null && !code.equals(""))
        .collect(Collectors.toList());
       
        descs.stream().forEach(System.out::println);
     }
}

How can I replace the line

.map(code -> getDesc( "AAA", code))

with something like

.map(code -> getDesc( cities.get(i), code))

in order to get all the descs.

Expected output

AAA_Descr_0  
AAA_Descr_1  
BBB_Descr_0  
BBB_Descr_1

Solution

  • You could try the following with IntStream. it streams a range from 0 to size exclusive, then gets each item in the list and provides it as arguments to your function. Not exactly as "dynamic" as you expect, but its as good as it gets

    public static void main(String []args){
       List<String> cities = Arrays.asList("AAA","AAA","BBB", "BBBB");
       List<String> codes = Arrays.asList("0","1","0","1");
       
       List<String> descs = IntStream.range(0, cities.size())
               .mapToObj(i -> getDesc(cities.get(i), codes.get(i)))
               .collect(Collectors.toList());
    //       List<String> descs = codes.stream()
    //        .map(code -> getDesc( "AAA", code))
    //        .distinct()
    //        .filter(code -> code != null && !code.equals(""))
    //        .collect(Collectors.toList());
       
        descs.stream().forEach(System.out::println);
     }
    

    output:

    AAA_Descr_0
    AAA_Descr_1
    BBB_Descr_0