0

I have a for loop, processing two string lists, which invokes a method with multiple parms, returning an object, which gets added to a List

I want to effectively utilize stream/lambda for this, can someone guide me I have two incoming string lists "AAA, BBB, CCC" and a corresponding list of quantities as "1, 3, 11"

final List<someObj> someObjs = new ArrayList<someObj>() ;

final List<String> codesList = Arrays.asList(codes.split("\\s*,\\s*"));
final List<String> qtysList  = Arrays.asList(qtys.split("\\s*,\\s*"));

for (String code: codesList){
    someObjs.add(addThis(code, qtysList.get(index++)));//
}

return someObj;

How can I convert this using lambdas ? Thanks in advance !

killjoy
  • 940
  • 1
  • 11
  • 16

1 Answers1

2

How about this,

final List<SomeObj> someObjs = IntStream.range(0, codesList.size())
        .mapToObj(i -> addThis(codesList.get(i), qtysList.get(i)))
        .collect(Collectors.toList());
Ravindra Ranwala
  • 20,744
  • 6
  • 45
  • 63
  • 1
    Genius! Thanks...This is turning out to be an art form :) Not to sound too greedy, but any way to incorporate the creation of the two String Lists from the comma delimited strings? I know it might make it unreadable, but was just wondering if it was at all possible. (Seems like there is no end to this stream magic.) – killjoy Jun 26 '18 at 17:19
  • Found the stream construct from Mohsen's answer https://stackoverflow.com/questions/27599847/convert-comma-separated-string-to-list-without-intermediate-container just need a way to plug it in I guess, if possible – killjoy Jun 26 '18 at 17:42
  • 1
    @killjoy this way it can be created: Collections.list(new StringTokenizer(str, ",")).stream() .map(token -> (String) token) .collect(Collectors.toList()) – Peter1982 Jun 26 '18 at 17:50