import java.util.*; import java.util.stream.*; public class CollectingDemo { public static void main(String[] args) { ArrayList<Integer> al = new ArrayList<>(); al.add(5); al.add(7); al.add(7); al.add(30); al.add(49); al.add(100); System.out.println("Actual List: " + al); Stream<Integer> odds = al.stream().filter(n -> n % 2 == 1); System.out.print("Odd Numbers: "); odds.forEach(n -> System.out.print(n + " ")); System.out.println(); List<Integer> oddList = al.stream().filter(n -> n % 2 == 1).collect(Collectors.toList()); System.out.println("The list: " + oddList); Set<Integer> oddSet = al.stream().filter(n -> n % 2 == 1).collect(Collectors.toSet()); System.out.println("The set: " + oddSet); } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter