Java Stream: divide into two lists by boolean predicate

Collectors.partitioningBy: Map<Boolean, List<Employee>> partitioned = listOfEmployees.stream().collect( Collectors.partitioningBy(Employee::isActive)); The resulting map contains two lists, corresponding to whether or not the predicate was matched: List<Employee> activeEmployees = partitioned.get(true); List<Employee> formerEmployees = partitioned.get(false); There are a couple of reasons to use partitioningBy over groupingBy (as suggested by Juan Carlos Mendoza): Firstly, the parameter of groupingBy is a Function<Employee, … Read more

Count the number of true members in an array of boolean values

Seems like your problem is solved already, but there are plenty of easier methods to do it. Excellent one: .filter(Boolean); // will keep every truthy value in an array const arr = [true, false, true, false, true]; const count = arr.filter(Boolean).length; console.log(count); Good one: const arr = [true, false, true, false, true]; const count = … Read more

How to call reduce on an empty Kotlin array?

The exception is correct, reduce does not work on an empty iterable or array. What you’re probably looking for is fold, which takes a starting value and an operation which is applied successively for each element of the iterable. reduce takes the first element as a starting value, so it needs no additional value to … Read more

python histogram one-liner [duplicate]

Python 3.x does have reduce, you just have to do a from functools import reduce. It also has “dict comprehensions”, which have exactly the syntax in your example. Python 2.7 and 3.x also have a Counter class which does exactly what you want: from collections import Counter cnt = Counter(“abracadabra”) In Python 2.6 or earlier, … Read more