-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReturnOnlytheInt.java
More file actions
41 lines (31 loc) · 858 Bytes
/
ReturnOnlytheInt.java
File metadata and controls
41 lines (31 loc) · 858 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
returnInts([9, 2, "space", "car", "lion", 16]) ➞ [9, 2, 16];
returnInts(["hello", 81, "basketball", 123, "fox"]) ➞ [81, 123];
returnInts([10, "121", 56, 20, "car", 3, "lion"]) ➞ [10, 56, 20, 3];
returnInts(["String", true, 3.3, 1]) ➞ [1]
//Solution;
import java.util.*;
public class Program {
public static int[] returnInts(Object[] arr) {
List<Integer> list = new ArrayList<>();
for(Object obj: arr){
if(obj instanceof Integer){
list.add((int) obj);
}
}
int[] intArr = new int[list.size()];
for(int i=0;i< list.size();i++){
intArr[i] = list.get(i);
}
return intArr;
}
}
//Solution2;
import java.util.Arrays;
public class Program {
public static int[] returnInts(Object[] arr) {
return Arrays.stream(arr)
.filter(o -> o instanceof Integer)
.mapToInt(o -> (int) o)
.toArray();
}
}