javafor-loopfilterjava-stream

How to convert to "filter" from for loop


I have a simple for loop and I want to change it into a statement using filter

for (int lotto_num: lottos) {
    if (lotto_num == 0) {
        unknown_count++;
    }
    
    for (int win_num : win_nums) {
        if (lotto_num == win_num) {
            count ++;
        }
    }
}

is it possible? I dont't really know how to use filter and stream.


Solution

  • In order to use Java's Stram API you should firstly convert your int[] arrays win_nums and lottos to List<Integer>.

    It can be done this way:

    List<Integer> win_nums_list = IntStream.of(win_nums).boxed().collect(Collectors.toList());
    
    List<Integer> lottos_list= IntStream.of(lottos).boxed().collect(Collectors.toList());
    

    Now we can use Stream API to get the desired result.

    int count = win_nums_list.stream().filter(win_num -> lottos_list.contains(win_num)).count();
    
    int unknown_count = lottos_list.stream().filter(lotto -> lotto== 0).count();
    

    with adding imports to the beginning of your code:

    import java.util.*;