Объясните пожалуйста вот этот код:
TreeSet<Station> connectedStations = connections.get(station);
connectedStations.addAll(stations.stream()
.filter(s -> !s.equals(station)).collect(Collectors.toList()))
Как этот код добавляет в TreeMap<Station, TreeSet<Station>> connections
элемент(ы)?
На вход в метод addConnection()
передается ArrayList<Station> stations
, содержащий 2 объекта Fourth
и Violet
.
Первый объект из ArrayList
передается в TreeMap
с ключем-объект , а значение создается пустой TreeSet()
.
После выхода из итерации цикла for
значение TreeSet<Station> connectedStations
кажется, что никуда не передаются. Однако после исполнения этого кода объект добавляется в связку ключ-значение в connections
(key: Fourth -> value: Violet).
Пытался отследить изменения при выполнении кода через дебаггер в IJ Idea, но так и не понял.
import core.Line;
import core.Station;
import java.util.*;
import java.util.stream.Collectors;
public class StationIndex
{
HashMap<Integer, Line> number2line;
TreeSet<Station> stations;
TreeMap<Station, TreeSet<Station>> connections;
public StationIndex()
{
number2line = new HashMap<>();
stations = new TreeSet<>();
connections = new TreeMap<>();
}
public void addStation(Station station)
{
stations.add(station);
}
public void addLine(Line line)
{
number2line.put(line.getNumber(), line);
}
public void addConnection(List<Station> stations)
{
for(Station station : stations)
{
if(!connections.containsKey(station)) {
connections.put(station, new TreeSet<>());
}
TreeSet<Station> connectedStations = connections.get(station);
connectedStations.addAll(stations.stream()
.filter(s -> !s.equals(station)).collect(Collectors.toList()));
}
}
public Line getLine(int number)
{
return number2line.get(number);
}
public Station getStation(String name)
{
for(Station station : stations)
{
if(station.getName().equalsIgnoreCase(name)) {
return station;
}
}
return null;
}
public Station getStation(String name, int lineNumber)
{
Station query = new Station(name, getLine(lineNumber));
Station station = stations.ceiling(query);
return station.equals(query) ? station : null;
}
public Set<Station> getConnectedStations(Station station)
{
if(connections.containsKey(station)) {
return connections.get(station);
}
return new TreeSet<>();
}
}