简体   繁体   中英

How do I iterate through two streams using java 8 lambda expressions and keeping a count

I have two lists streams one of strings (counties) and one of objects(txcArray). I need to iterate through both lists and compare an instance of counties with an instance of txcArray and they match increment a counter and if they don't I would move on. I need to do this using java 8 lambda expressions and this is what I have so far.

counties.stream().forEach(a-> {
     txcArray.stream()
             .filter(b->b.getCounty().equals(a))
             .map(Map<String,Integer>)
});

Your mistake is using forEach .

List<Long> counts = counties.stream()
    .map(a -> txcArray.stream().filter(b -> b.getCounty().equals(a)).count())
    .collect(Collectors.toList());

However, this is not very efficient, performing counties.size() × txcArray.size() operations. This can get out of hands easily, when the lists are larger.

It's better to use

Map<String, Long> map = txcArray.stream()
    .collect(Collectors.groupingBy(b -> b.getCounty(), Collectors.counting()));
List<Long> counts = counties.stream()
    .map(a -> map.getOrDefault(a, 0L))
    .collect(Collectors.toList());

This will perform counties.size() + txcArray.size() operations, which will be more efficient for larger lists, therefore, preferable, even if it's not a single stream operation but using an intermediate storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM