使用java中的Collectors从两个哈希映射返回平均值

Car*_*ein 3 java functional-programming

我有两个哈希图:busStopsbusServices.

两者在多对多关系中彼此链接,即一个公共汽车站可以有许多服务,一个服务可以有许多公共汽车站.

Hashmap.java - busStops和busServices都是这样的实例.

class HashMapO<K,V> {
  private HashMap<K,V> map;

  public HashMapO() {
    map = new HashMap<>();
  }

  public void put(K key, V value) {
    map.put(key, value);
  }

  public Optional<V> get(K key) {
    return Optional.ofNullable(map.get(key));
  }

  public Stream<Map.Entry<K,V>> entries() {
    return map.entrySet().stream();
  }
}
Run Code Online (Sandbox Code Playgroud)

averageStops.java

  public double averageNumberOfBusesPerStop() {
    double results = busStops.entries()
//return a stream of key value entries in busStops' hashmap.

        .filter(x -> x.getValue().getBusServices())
//for each entry, get the value(e.g. the busStop) and return a stream of services for that stop.

        .collect(Collectors.averagingDouble());
//not sure how to implement collector here.
    return results;
  }
Run Code Online (Sandbox Code Playgroud)

BusStop.java

class BusStop {
  public BusStop(String name){
    this.name = name;
    buses = new HashSet<>();
  }
  public Stream<BusService> getBusServices() {
    return buses.stream();
  }
  public boolean add(BusService bus) {
    return buses.add(bus);
  }
    }
Run Code Online (Sandbox Code Playgroud)

我希望找到每个站点平均总线数量以及使用Java收集器停止最多总线.

And*_*eas 5

您的代码有两个错误:

  • filter需要一个boolean价值.你的lambda返回一个Stream.

  • averagingDouble需要一个double价值.你甚至没有给一个.

假设您添加了filter不包含服务的排除公交车站,您的代码将是:

double average = busStops.entries()
    .filter(e -> e.getValue().getBusServices().anyMatch(x -> true))
    .collect(Collectors.averagingDouble(e -> e.getValue().getBusServices().count()));
Run Code Online (Sandbox Code Playgroud)

要么:

double average = busStops.entries()
    .mapToDouble(e -> e.getValue().getBusServices().count())
    .filter(cnt -> cnt != 0)
    .average();
Run Code Online (Sandbox Code Playgroud)

访问底层size()方法的代码将大大受益,因此它不必流和计数,但我相信Java 9优化了它,所以entrySet().stream().count()实际上只是调用size().