Aspirer
Aspirer

Reputation: 55

How to optimize nested for each loops

I wanted to optimize the below code. Will streams optimize the below nested foreach loops? If so am new to streams can someone please help me? In the below I have replaced the names for project confidentiality purpose. Shall be using the tList for further processing in the code. Can some one please help on this?

List<Tea> tea = requestBody.getTea();
            
for (Tea tea1 : teas) {
    List<String> teaValues = tea1.getTeaValues();
    for (String t : teaValues) {
        if ((t).contains("tMapping") || ((t).contains("tdata"))) {
            int subStrng = t.indexOf(".") + 1;
            int subStrngSpace = t.indexOf(" ");
            String tStrng = t.substring(subStrng, subStrngSpace);
            tList.add(tStrng);
        } else {
            String[] tStrng = t.split("\'");
                String t1 = tStrng[1];
                tList.add(t1);
            
        }
    }
}

Upvotes: 1

Views: 427

Answers (1)

Arthur Klezovich
Arthur Klezovich

Reputation: 2817

Will streams optimize the below nested foreach loops?

No, not really. Unless you have a really big input and you're using a server with multiple processes/cores, then you can get a speed up from using parallel streams.

Otherwise, these streams will just be converted into loops "under the hood" ...

This is to answer your question.

Now let's look at the question behind the question ... why do you want to optimise it ? How will you know that your optimisation level is good enough ?

EDIT:

  1. If this is to be designed to handle super big inputs you need to make use of concurrency. The easiest way to do it would be to use parallel streams.
  2. Even better would be to move this processing code from the application into the database. It will be able to process this even faster. Just write a native query (see here) which does all the transforms of data within the database.

Upvotes: 3

Related Questions