-1

I am trying to append indexes with constants and get some sql. Currently I am just iterating over a list using for loop. I am looking for better ways of doing the same.

List<String> list1 = new ArrayList<>();
Integer index = 0;

for (String str : listToIterate) {
    String param1 = "PARAM" + index;
    String prefixParam1 = "PARAM_PREFIX" + index;
    list1.add(getSomeParameterisedSql(param1, prefixParam1, str));
    index = index + 1;
}
5
  • 1
    Why do you want to have better ways ? Are you having any performance issues ? Or you want to shorten the code ? Commented May 30, 2022 at 6:23
  • What is wrong with the current method? Commented May 30, 2022 at 6:23
  • 1
    How about formatting/indentation? That would be a guaranteed win.
    – Filburt
    Commented May 30, 2022 at 6:26
  • 1
    For general help on writing code you could have a look at softwareengineering.stackexchange.com
    – René Jahn
    Commented May 30, 2022 at 6:26
  • You could use a regular for loop instead of a for-each and use the counter as index, but that would just shorten this code by two lines.
    – deHaar
    Commented May 30, 2022 at 6:27

1 Answer 1

1

I hope you are using Java 8, if so below code might work for you

    List<String> listOfSqls = IntStream.range(0,listToIterate.size())
        .mapToObj(index -> getSomeParameterisedSql("PARAM" + index, "PARAM_PREFIX" + index, listToIterate.get(index)))
        .collect(Collectors.toList());
2
  • I am using Java11
    – itisha
    Commented May 30, 2022 at 9:09
  • 1
    @itisha Java 11 is backwards compatible with Java 8. Commented May 30, 2022 at 9:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.