public List function(List A, List B) { List C = new ArrayList<>(); Map howManyTimesAppearsInList = B.stream() .collect(Collectors.groupingBy(x -> x, Collectors.counting())); for (int element : A) { Long occurrences = howManyTimesAppearsInList.get(element); if (occurrences == null) { C.add(element); } else { if (occurrences == 1) { C.add(element); } else { for (int j = 2; j < element; j++) { if (element % j == 0) { C.add(element); break; } } } } } return C; }