Use Java stream to get the index of Min size list in ArrayList

I have a list of integers, such as LIST1 = (1,2,3) and List2 = (0,1)

My list contains LIST1 and List2 It can contain more, but I only use two lists for the example

The problem is to use the Java stream to get the minimum size list index

This is my program. It only uses the for loop method

import java.util.ArrayList;

public class Example {

     public static void main( String[] args ) {


         ArrayList<Integer> list1 = new ArrayList<>();
         list1.add(1);list1.add(2);list1.add(3);

         ArrayList<Integer> list2 = new ArrayList<>();
         list2.add(0);list2.add(1);

         ArrayList<ArrayList<Integer>> listOLists = new ArrayList<>();
         listOLists.add(list1);
         listOLists.add(list2);
         printTheIndexOfTheListWithTheMinSize(listOLists);
     }

    private static void printTheIndexOfTheListWithTheMinSize( ArrayList<ArrayList<Integer>> listOLists ) {
        int minSize  = listOLists.get(0).size();
        int minIndex = 0;
        int i=0;
        for ( ArrayList<Integer> list:  listOLists ) {

            if (list.size()<minSize)
            {
                minSize = list.size();
                minIndex=i;
            }
            i++;

        }
        Sy@R_403_2354@.out.println(minIndex);
    }
}

Could you please show me how to do this using the Java streaming API

Note that I call this method many times in heavy calculations, so awnser should take this into account

Solution

Not very elegant, because it needs boxing and unpacking, but

Optional<Integer> minIndex = 
    IntStream.range(0,list.size())
             .@R_649_2419@ed()
             .min(Comparator.comparingInt(i -> list.get(i).size()));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>