get the index of the min size list in an arrayList using java stream

zak zak :

I have a list of Integer List, like list1=(1,2,3) and list2 = (0,1).

my list of lists contains list1 and list2. It could contains more but for the example i took only two lists.

The question is to get the index of the list with minimum size using java stream.

Here is my program and it work using only 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++;

        }
        System.out.println(minIndex);
    }
}

Could you please give me a hint how to do that using Java stream API.

Note that i'm calling this method many times in a heavy calcul, so the awnser should take that in consideration.

JB Nizet :

Not really elegant, because it requires boxing and unboxing, but...

Optional<Integer> minIndex = 
    IntStream.range(0, list.size())
             .boxed()
             .min(Comparator.comparingInt(i -> list.get(i).size()));

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84772&siteId=1