-1

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.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
honey_bee
  • 13
  • 3
  • Do you have example values for the variables `lottos` and `win_nums`? Can you show them? – deHaar Apr 21 '22 at 08:26
  • Hint: *I have a simple for loop* is not quite correct, you have 2 for loops of which one is even nested. That's not really *simple* anymore… – deHaar Apr 21 '22 at 08:29
  • 1
    `.filter()` is used to remove specific elements from a stream/collection. Your logic doesn't seem to be filtering. It produces two separate values that aren't attached to any specific element in the collection. – Ivar Apr 21 '22 at 08:30
  • lottos = [44, 1, 0, 0, 31, 25] , win_nums = [31, 10, 45, 1, 6, 19] – honey_bee Apr 21 '22 at 08:33
  • @honey_bee What exactly your code should do? Count the number of intersections of `win_nums` and `lottos`? – Levon Minasian Apr 21 '22 at 08:35

1 Answers1

0

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.*;
Levon Minasian
  • 531
  • 1
  • 5
  • 17
  • Oh I need to convert array to List. Is there a way using Arrays.stream() ~ ? (Just curiosity) And I really appreciate you for letting me know. :) – honey_bee Apr 21 '22 at 08:53
  • Yes, exactly. I've edited my answer and presented you the way to do it with Stream API – Levon Minasian Apr 21 '22 at 08:56
  • See here also https://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java?noredirect=1&lq=1 – Levon Minasian Apr 21 '22 at 08:57
  • Thank you !! I hope you have a nice day :) – honey_bee Apr 21 '22 at 08:58
  • @honey_bee if this or any answer has solved your question please consider accepting it by clicking the check-mark. This indicates to the wider community that you've found a solution and gives some reputation to both the answerer and yourself. There is no obligation to do this. See here https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work – Levon Minasian Apr 21 '22 at 09:08