3

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>)
});
Naman
  • 27,789
  • 26
  • 218
  • 353
Octavio garcia
  • 107
  • 2
  • 5
  • 1
    I think you meant: you have "two lists" and not "two lists streams"? So you only want to count how many items in your list of strings match in the array of objects regarding your predicate? If so: forget about `.forEach` and try to solve it using `.filter` and `.count()` first. If it works, you can continue with `.map` to transform your object into a country string before filtering. At the end you may even want to try to use method references. I wouldn't start with Grisha's suggestion regarding `zip` as it seems more complicated for what you are trying to solve. – Roland Oct 10 '17 at 06:15
  • Let me phrase the question again. I have a list of type string and another lis of type texasCitiesClass(txcArray). texasCitiesClass contains, city name, county, and population. I have all the unique counties in the counties list. What I need to do is check how many times each instance in counties appears in txcArray and add this number for each county into another list of type integer or long. The constraints is that I am oniy supposed to do this using streams and lambda expressions. Thank you for your help, Grisha and Roland – Octavio garcia Oct 10 '17 at 06:26

1 Answers1

6

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.

Holger
  • 285,553
  • 42
  • 434
  • 765