MATSIM
NetworkCollector.java
Go to the documentation of this file.
1 package org.matsim.core.network;
2 
7 
8 import java.util.Collection;
9 import java.util.Set;
10 import java.util.concurrent.ConcurrentHashMap;
11 import java.util.function.BiConsumer;
12 import java.util.function.BinaryOperator;
13 import java.util.function.Function;
14 import java.util.function.Supplier;
15 import java.util.stream.Collector;
16 import java.util.stream.Stream;
17 
24 public class NetworkCollector implements Collector<Link, Collection<Link>, Network> {
26 
30  NetworkCollector(NetworkConfigGroup networkConfigGroup) {
31  this.networkConfigGroup = networkConfigGroup;
32  }
33 
34  private static void addNodeIfNecessary(Network network, Node node) {
35  if (!network.getNodes().containsKey(node.getId())) {
36 
37  // nodes keep internal state of in- and out-links. Since we don't know, whether this state is stale at this
38  // point we create a shallow copy with empty in-out-links mappings. Simply clearing the mappings would alter the
39  // state in the original network, which would be unexpected behaviour of a collector.
40  var copy = NetworkUtils.createNode(node.getId());
41  copy.setCoord(node.getCoord());
42 
43  for (var entry : node.getAttributes().getAsMap().entrySet()) {
44  copy.getAttributes().putAttribute(entry.getKey(), entry.getValue());
45  }
46  network.addNode(copy);
47  }
48  }
49 
50  @Override
51  public Supplier<Collection<Link>> supplier() {
52  // return a concurrent set because we want 'concurrent' characteristics
53  return ConcurrentHashMap::newKeySet;
54  }
55 
56  @Override
57  public BiConsumer<Collection<Link>, Link> accumulator() {
58  return Collection::add;
59  }
60 
61  @Override
62  public BinaryOperator<Collection<Link>> combiner() {
63  return (links, links2) -> {
64  links.addAll(links2);
65  return links;
66  };
67  }
68 
69  @Override
70  public Function<Collection<Link>, Network> finisher() {
71  return links -> {
72 
73  var result = NetworkUtils.createNetwork(networkConfigGroup);
74  for (var link : links) {
75  addNodeIfNecessary(result, link.getFromNode());
76  addNodeIfNecessary(result, link.getToNode());
77  result.addLink(link);
78  }
79  return result;
80  };
81  }
82 
83  @Override
84  public Set<Characteristics> characteristics() {
85  return Set.of(Characteristics.UNORDERED, Characteristics.CONCURRENT);
86  }
87 }
Function< Collection< Link >, Network > finisher()
Map< Id< Node >, ? extends Node > getNodes()
BiConsumer< Collection< Link >, Link > accumulator()
Supplier< Collection< Link > > supplier()
BinaryOperator< Collection< Link > > combiner()
static void addNodeIfNecessary(Network network, Node node)
static Node createNode(Id< Node > id)