I have the list of int - 2, 3, 6, 8, 14, 15, 9, 4.
I want to search such numbers whose square is present in the list, ex: 2 square 4 is present, so the output list should have 2.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamTest {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(2, 3, 6, 8, 14, 15, 9, 4);
System.out.println(
list.stream()
.map(i -> hasSquare(i, list))
.distinct()
.collect(Collectors.toList()));
}
private static Object hasSquare(Integer i, List<Integer> list) {
if (list.contains(i * i)) {
return i;
} else {
return 0;
}
}
}
This code is giving me the output [2, 3, 0], but I would like to get rid of 0.
Is there a way to do the same without using a third method?