Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package mountainhuts;
- import static java.util.stream.Collectors.toList;
- import java.io.BufferedReader;
- import java.io.FileReader;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.Collection;
- import java.util.Collections;
- import java.util.Comparator;
- import java.util.HashMap;
- import java.util.HashSet;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.Optional;
- import java.util.TreeMap;
- import java.util.stream.Collectors;
- import java.util.stream.Stream;
- public class Region {
- private String name;
- private Collection<Range> ranges;
- private Collection<Municipality> municipalities;
- private Collection<MountainHut> mountainHuts;
- /**
- * Create a region with the given name.
- *
- * @param name
- * the name of the region
- */
- public Region(String name) {
- this.name = name;
- this.ranges = new ArrayList<>();
- this.municipalities = new ArrayList<>();
- this.mountainHuts = new ArrayList<>();
- }
- /**
- * Return the name of the region.
- *
- * @return the name of the region
- */
- public String getName() {
- return this.name;
- }
- /**
- * Create the ranges given their textual representation in the format
- * "[minValue]-[maxValue]".
- *
- * @param ranges
- * an array of textual ranges
- */
- public void setAltitudeRanges(String... ranges) {
- for(String s : ranges) {
- String[] temp = s.split("-");
- this.ranges.add(new Range(Integer.parseInt(temp[0]),Integer.parseInt(temp[1])));
- }
- }
- /**
- * Return the textual representation in the format "[minValue]-[maxValue]" of
- * the range including the given altitude or return the default range "0-INF".
- *
- * @param altitude
- * the geographical altitude
- * @return a string representing the range
- */
- public String getAltitudeRange(Integer altitude) {
- for(Range r : ranges) {
- if(r.isInRange(altitude))
- return r.toString();
- }
- return "0-INF";
- }
- /**
- * Return all the municipalities available.
- *
- * @return a collection of municipalities
- */
- public Collection<Municipality> getMunicipalities() {
- return this.municipalities;
- }
- /**
- * Return all the mountain huts available.
- *
- * @return a collection of mountain huts
- */
- public Collection<MountainHut> getMountainHuts() {
- return this.mountainHuts;
- }
- /**
- * Create a new municipality if it is not already available or find it.
- * Duplicates must be detected by comparing the municipality names.
- *
- * @param name
- * the municipality name
- * @param province
- * the municipality province
- * @param altitude
- * the municipality altitude
- * @return the municipality
- */
- public Municipality createOrGetMunicipality(String name, String province, Integer altitude) {
- Municipality mun = new Municipality (name,province,altitude);
- for(Municipality m : municipalities) {
- if(m.getName().compareTo(name) == 0)
- return m;
- }
- municipalities.add(mun);
- return mun;
- }
- /**
- * Create a new mountain hut if it is not already available or find it.
- * Duplicates must be detected by comparing the mountain hut names.
- *
- * @param name
- * the mountain hut name
- * @param category
- * the mountain hut category
- * @param bedsNumber
- * the number of beds in the mountain hut
- * @param municipality
- * the municipality in which the mountain hut is located
- * @return the mountain hut
- */
- public MountainHut createOrGetMountainHut(String name, String category, Integer bedsNumber,
- Municipality municipality) {
- return createOrGetMountainHut(name, null, category, bedsNumber, municipality);
- }
- /**
- * Create a new mountain hut if it is not already available or find it.
- * Duplicates must be detected by comparing the mountain hut names.
- *
- * @param name
- * the mountain hut name
- * @param altitude
- * the mountain hut altitude
- * @param category
- * the mountain hut category
- * @param bedsNumber
- * the number of beds in the mountain hut
- * @param municipality
- * the municipality in which the mountain hut is located
- * @return a mountain hut
- */
- public MountainHut createOrGetMountainHut(String name, Integer altitude, String category, Integer bedsNumber,
- Municipality municipality) {
- MountainHut mouH = new MountainHut(name,category,municipality,Optional.ofNullable(altitude),bedsNumber);
- for(MountainHut mh : mountainHuts) {
- if(mh.getName().compareTo(name) == 0)
- return mh;
- }
- mountainHuts.add(mouH);
- return mouH;
- }
- /**
- * Creates a new region and loads its data from a file.
- *
- * The file must be a CSV file and it must contain the following fields:
- * <ul>
- * <li>{@code "Province"},
- * <li>{@code "Municipality"},
- * <li>{@code "MunicipalityAltitude"},
- * <li>{@code "Name"},
- * <li>{@code "Altitude"},
- * <li>{@code "Category"},
- * <li>{@code "BedsNumber"}
- * </ul>
- *
- * The fields are separated by a semicolon (';'). The field {@code "Altitude"}
- * may be empty.
- *
- * @param name
- * the name of the region
- * @param file
- * the path of the file
- */
- public static Region fromFile(String name, String file) {
- Region region = new Region(name);
- region.readData(file);
- return region;
- }
- @SuppressWarnings("unused")
- private void readData(String file) {
- List<String> lines = null;
- try (BufferedReader in = new BufferedReader(new FileReader(file))) {
- lines = in.lines().collect(toList());
- } catch (IOException e) {
- System.err.println(e.getMessage());
- }
- if (lines == null)
- return;
- Iterator<String> iterator = lines.iterator();
- String line = iterator.next();
- while(iterator.hasNext()) {
- line = iterator.next();
- String campi[] = line.split(";");
- if(campi[4].compareTo("") == 0)
- campi[4] = campi[2];
- this.createOrGetMountainHut(
- campi[3],
- new Integer(Integer.parseInt(campi[4])),
- campi[5],
- new Integer(Integer.parseInt(campi[6])),
- this.createOrGetMunicipality(campi[1], campi[0], new Integer(Integer.parseInt(campi[2]) )
- )
- );
- }
- }
- /**
- * Count the number of municipalities with at least a mountain hut per each
- * province.
- *
- * @return a map with the province as key and the number of municipalities as
- * value
- */
- public Map<String, Long> countMunicipalitiesPerProvince() {
- return municipalities.stream().collect(Collectors.groupingBy( Municipality :: getProvince,
- () -> new HashMap<>(), Collectors.counting() ) );
- }
- /**
- * Count the number of mountain huts per each municipality within each province.
- *
- * @return a map with the province as key and, as value, a map with the
- * municipality as key and the number of mountain huts as value
- */
- public Map<String, Map<String, Long>> countMountainHutsPerMunicipalityPerProvince() {
- return mountainHuts.stream().collect(Collectors.groupingBy(
- m -> m.getMunicipality().getProvince(), () -> new HashMap<>(), Collectors.groupingBy(
- m-> m.getMunicipality().getName(),() -> new HashMap<>(), Collectors.counting()
- )
- )
- );
- }
- /**
- * Count the number of mountain huts per altitude range. If the altitude of the
- * mountain hut is not available, use the altitude of its municipality.
- *
- * @return a map with the altitude range as key and the number of mountain huts
- * as value
- */
- public Map<String,Long> countMountainHutsPerAltitudeRange() {
- return this.mountainHuts.stream().collect(Collectors.groupingBy(
- (MountainHut mh) -> {
- if(mh.getAltitude().isPresent())
- return this.getAltitudeRange(mh.getAltitude().get());
- else
- return this.getAltitudeRange(mh.getMunicipality().getAltitude());
- },
- () -> new HashMap<>(),
- Collectors.counting()
- )
- );
- }
- /* Senza stream:
- Map<String,Long> mappa = new HashMap<>();
- Integer altezza;
- for(Range r : ranges) {
- long conta = 0;
- for(MountainHut m : mountainHuts) {
- if ( m.getAltitude().isPresent() )
- altezza = m.getAltitude().get();
- else
- altezza = m.getMunicipality().getAltitude();
- if(r.isInRange(altezza) == true)
- conta++;
- }
- mappa.put(r.toString(), new Long(conta));
- }
- return mappa;
- }*/
- /**
- * Compute the total number of beds available in the mountain huts per each
- * province.
- *
- * @return a map with the province as key and the total number of beds as value
- */
- public Map<String, Integer> totalBedsNumberPerProvince() {
- return this.mountainHuts.stream().collect(Collectors.groupingBy(
- m -> m.getMunicipality().getProvince(), () -> new HashMap<>(), Collectors.summingInt(MountainHut :: getBedsNumber)
- )
- );
- }
- /**
- * Compute the maximum number of beds available in a single mountain hut per
- * altitude range. If the altitude of the mountain hut is not available, use the
- * altitude of its municipality.
- *
- * @return a map with the altitude range as key and the maximum number of beds
- * as value
- */
- public Map<String, Optional<Integer>> maximumBedsNumberPerAltitudeRange() {
- return this.mountainHuts.stream().collect(Collectors.groupingBy(
- (MountainHut mh) -> {
- if(mh.getAltitude().isPresent())
- return this.getAltitudeRange(mh.getAltitude().get());
- else
- return this.getAltitudeRange(mh.getMunicipality().getAltitude());
- },
- () -> new HashMap<>(),
- Collectors.mapping(
- MountainHut :: getBedsNumber,
- Collectors.maxBy(Integer :: compareTo)
- )
- )
- );
- }
- /*Senza stream:
- Map<String,Optional<Integer>> mappa = new HashMap<>();
- Integer altezza;
- for(Range r : ranges) {
- int max = 0;
- for(MountainHut mh : mountainHuts) {
- if ( mh.getAltitude().isPresent() )
- altezza = mh.getAltitude().get();
- else
- altezza = mh.getMunicipality().getAltitude();
- int nBeds = mh.getBedsNumber();
- if(r.isInRange(altezza) && max < nBeds)
- max = nBeds;
- }
- mappa.put(r.toString(), Optional.ofNullable(max));
- }
- return mappa;/*
- }
- /**
- * Compute the municipality names per number of mountain huts in a municipality.
- * The lists of municipality names must be in alphabetical order.
- *
- * @return a map with the number of mountain huts in a municipality as key and a
- * list of municipality names as value
- */
- public Map<Long, List<String>> municipalityNamesPerCountOfMountainHuts() {
- /* Due stream separati
- Map<String,Long> primaParte = this.mountainHuts.stream().collect( Collectors.groupingBy(
- (MountainHut mountainHut) -> mountainHut.getMunicipality().getName(),
- () -> new TreeMap<String,Long>(),
- Collectors.counting())
- );
- Map<Long, List<String>> secondaParte = primaParte.entrySet().stream().collect( Collectors.groupingBy(
- Map.Entry :: getValue,
- Collectors.mapping(
- Map.Entry :: getKey,
- Collectors.toList() )
- )
- );
- return secondaParte; */
- return this.mountainHuts.stream().collect( Collectors.groupingBy(
- (MountainHut mountainHut) -> mountainHut.getMunicipality().getName(), //classifier
- () -> new TreeMap<String,Long>(),
- Collectors.counting() //downstream
- ) ).entrySet().stream().collect( Collectors.groupingBy(
- Map.Entry :: getValue,
- Collectors.mapping(
- Map.Entry :: getKey,
- Collectors.toList()
- )
- )
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement