A collector may be used for this.
- For two categories, use
Collectors.partitioningBy() factory.
This will create a Map from Boolean to List and put the items in one or another list based on Predicate .
Note. Since a thread needs to be consumed in its entirety, it cannot work on endless threads. Since the stream is still consumed, this method simply puts them in lists instead of creating a new stream with memory.
In addition, there is no need for an iterator, not even an example with the headers you provided.
Random r = new Random(); Map<Boolean, List<String>> groups = stream .collect(Collectors.partitioningBy(x -> r.nextBoolean())); System.out.println(groups.get(false).size()); System.out.println(groups.get(true).size());
- For more categories, use
Collectors.groupingBy() factory.
Map<Object, List<String>> groups = stream .collect(Collectors.groupingBy(x -> r.nextInt(3))); System.out.println(groups.get(0).size()); System.out.println(groups.get(1).size()); System.out.println(groups.get(2).size());
If the streams are not Stream , but one of the primitive streams, such as IntStream , then this .collect(Collectors) method is not available. You will have to do this manually without a factory collector. This implementation is as follows:
IntStream intStream = IntStream.iterate(0, i -> i + 1).limit(1000000); Predicate<Integer> p = x -> r.nextBoolean(); Map<Boolean, List<Integer>> groups = intStream.collect(() -> { Map<Boolean, List<Integer>> map = new HashMap<>(); map.put(false, new ArrayList<>()); map.put(true, new ArrayList<>()); return map; }, (map, x) -> { boolean partition = p.test(x); List<Integer> list = map.get(partition); list.add(x); }, (map1, map2) -> { map1.get(false).addAll(map2.get(false)); map1.get(true).addAll(map2.get(true)); }); System.out.println(groups.get(false).size()); System.out.println(groups.get(true).size());
Edit
As indicated, the above “workaround” is not thread safe. Going to normal Stream before building is the way to go:
Stream<Integer> stream = intStream.boxed();
Mark Jeronimus May 07, '15 at 20:17 2015-05-07 20:17
source share