Convert list <Long> to Map <Long, Long>, which takes into account occurrences
I play with Java 8, and I know that this should be possible by reading the documentation, I just can't figure out how to do this.
I have the following working code:
long factorProduct = LongStream.rangeClosed(1, maxFactor) .filter(this::isOptimalFactor) .reduce((i, j) -> i * j) .getAsLong(); List<Long> primeFactors = primeFactors(factorProduct); The important part is that I have a List<Long> which may have duplicates on some Long numbers.
Now I want to convert it to Map<Long, Long> with the key as an element and as an entry value.
I thought that:
Map<Long, Long> primeFactorCount = primeFactors.stream() .collect(Collectors.counting()); will work, but it is not. I looked through the examples in the java.util.stream.Collectors documentation .
How do I use these features?
If you want to group items, you should use groupingBy :
import static java.util.stream.Collectors.*; Map<Long, Long> primeFactorCount = primeFactors.stream() .collect(groupingBy(p -> p, counting())); If you use Eclipse Collections (formerly GS Collections ), you can use the following for a list of key factors and a counter of key factors. The bag is mainly Map<K, Integer> .
MutableList<Long> primeFactors = this.primeFactors(factorProduct); Bag<Long> primeFactorCount = primeFactors.toBag(); Use the FastList method in the primeFactors method above.
In the case of Eclipse Collections, we have primitive lists and packages, so you do not need to specify any results.
LongList primeFactors = this.primeFactors(factorProduct); LongBag primeFactorCount = primeFactors.toBag(); Use a LongArrayList instead in the primeFactors method above.
Note: I am a committer for Eclipse collections.