xmen-5
xmen-5

Reputation: 1906

Find the list with the minimum size over a list of list

I have a list of list and i want to return the list that have the min size using java Stream.

Here what i tried:

import java.util.ArrayList;
import java.util.Arrays;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class Example {
   public static void main( String[] args )  {
         ArrayList<Integer> list1 = new ArrayList<>();
         list1.add(0);list1.add(2);list1.add(3);

         ArrayList<Integer> list2 = new ArrayList<>();
         list2.add(0);list2.add(2);list2.add(3);list2.add(4);

         System.out.println( getTheMinList(list1,list2).size());    
   }

   public static ArrayList<Integer> getTheMinList(ArrayList<Integer>... lists) {
         return Arrays.stream(lists)
                      .map(list->list.size())
                      /*here i stoped*/
                ;
   }
}

The program should print 3 because the first list has the minimum size.

Note that I can't change the signature of the getTheMinList(). Could anyone please give me a hint?

Upvotes: 8

Views: 2810

Answers (2)

Ousmane D.
Ousmane D.

Reputation: 56443

Just another idea...

as @NullPointer suggested, I’d make the method take a List<List<Integer>> rather than the varargs.

Given this change you can simply do:

Collections.min(lists, Comparator.comparingInt(List::size)); 

Short, simple and readable right?

Note that the above will throw a NoSuchElementException upon the collection being empty which may aswell be the expected behaviour you’re wanting but just in case that’s not the the intended behaviour you may want to check for emptiness before the call to min or use the stream approach suggested by @NullPointer which uses the Optional API to return an alternative value if Stream#min returns an empty Optional.

Upvotes: 4

Naman
Naman

Reputation: 31958

You can use Stream.min comparing the List.size:

public static List<Integer> getTheMinList(List<Integer>... lists){
    return Arrays.stream(lists)
            .min(Comparator.comparingInt(List::size))
            .orElse(new ArrayList<>());
}

or possibly better if you could get rid of var-args and unchecked assignment

private static List<Integer> getTheMinList(List<List<Integer>> lists){
    return lists.stream()
            .min(Comparator.comparingInt(List::size))
            .orElse(new ArrayList<>());
}
// invoked as
System.out.println(getTheMinList(List.of(list1, list2)).size());

Upvotes: 6

Related Questions