I am new to Java 8. I tried several ways to use the Streams API to solve the problem where we have been given an array of int = {48, 44, 4, 88, 84, 16, 12, 13 }. All I am trying to do is to find the occurrence of digit 4 in the whole array. I tried the following code -
int[] array = new int[] {48,44,4,88,84,16,12,13};
List<Integer> list = new ArrayList<Integer>();
for(int i:array) {
list.add(i);
}
List<Integer> l = list.stream().filter(n->n%10)
.map(n->n%10)
.collect(Collectors.toList());
System.out.println(l);
Please advice the Streams API way to solve this.
First, you need to obtain a stream from the given array of
int[]. You can do it either by using the static methodIntStream.of, or withArraysutility class and it's methodstream().Both will give you an
IntStream- a stream ofintprimitives. In order to collect stream elements into a list you need to convert it to a stream of objects. For that you can apply methodboxed()on the stream pipeline and eachintelement will get wrapped withIntegerobject.In order to find all elements in the given list that contain a target digit (
4), you can turn the target digit into a string and then apply afilterbased on it.main()Output
Note: method
filter()expects aPredicate(a function represented by a boolean condition, that takes an element and returntrueoffalse)Your attempt to create a predicate
filter(n -> n % 10)is incorrect syntactically and logically.n % 10doesn't produce a boolean value, it'll give the right most digit ofn.If you want to use modulus (
%) operator to create a predicate, you have to divide the element by10in a loop until it'll not become equal to0. And check before every division weather remainder is equal to the target digit. It could be done like that:You can utilize this method inside a lambda expression like that (note: it's a preferred way to avoid multiline lambda expressions by extracting them into separate methods)