-3

I have an ArrayList like below

ArrayList<String> fList = new ArrayList<>();
    fList.add("100510-0001");
    fList.add("100510-0001");
    fList.add("100513-0004");
    fList.add("100510-0002");
    fList.add("100510-0001");
    fList.add("100513-0005");
    fList.add("100513-0006");
    fList.add("100518-0006");
    fList.add("100599-0001");
    fList.add("100593-0009");

I need to send an email based on first 6 characters of the List values.

Example: I have 100510 repeated 4 times in the list so I need to send all 4 records in the same email, like below hardcode one.

I have 100513 3 times, I can have n number of lists but I need to do recursion/iteration and send the email with the same records i.e 100510 in a separate email and 100513 in a separate email etc...

Any help?

ArrayList<String> subList = new ArrayList<>();
    for (int i = 0; i < fList.size(); i++) {
       String subString =  fList.get(0).split("-")[0];
        if(fList.get(i) == "100510"){
            subList.add(fList.get(i));
            createEmail(subList);
        }
        if(fList.get(i) == "100513"){
            subList.add(fList.get(i));
            createEmail(subList);
        }
    }

2 Answers2

2

If all you need is to send one e-mail per "prefix", then all you need to do is group:

Map<String, List<String>> distinctMap = fList.stream()
            .collect(Collectors.groupingBy(s -> s.split("-")[0]));

distinctMap.forEach((str1, list) -> {
    System.out.println("Sending e-mail for prefix " + str1);
    createEmail(list);
});

Of course you can do that using your for-loop, but you should only send the e-mail after all iterations:

Map<String, List<String>> emailsByPrefix = new HashMap<>();

for (int i = 0; i < fList.size(); i++) {

    String subString = fList.get(i).split("-")[0];

    emailsByPrefix.merge(subString, Arrays.asList(fList.get(i)), (list1, list2) -> {
        List<String> merged = new ArrayList<>();
        merged.addAll(list1);
        merged.addAll(list2);

        return merged;
    });
}

for (Entry<String, List<String>> emailEntry : emailsByPrefix.entrySet()) {
    System.out.println("Sending e-mail for prefix " + emailEntry.getKey());
    createEmail(emailEntry.getValue());
}
ernest_k
  • 44,416
  • 5
  • 53
  • 99
-1

You can sort the original list, collect subList until first part changes, then send the subList each time the first part changes.

Collections.sort(fList);
String lastPart1 = null;
List<String> subList = null;
for (int i = 0; i < fList.size(); i++) {
   String strPart1 =  fList.get( i ).split("-")[0];
   String strPart2 =  fList.get( i ).split("-")[1];
    if( !strPart1.equals(lastPart1) ){
         if(subList!=null){ //Send the last collected subList
             createEmail( lastPart1, subList );
         }
         subList = new ArrayList<>();
         subList.add (strPart2);
         lastPart1 = strPart1;

    }else{
         subList.add (strPart2);
    }
}
Teddy
  • 4,009
  • 2
  • 33
  • 55