public static void main(String[] args) { int[] input = {2, 1, 4, 3, 6, 10, 8, 5, 9, 7}; List list1 = new Q(input); List list2 = new I(input); List list3 = new B(input); list1.sort(); list2.sort(); list3.sort(); }
public void writeTasks(OutputStream output) { try { output.write("[\n".getBytes()); boolean needComma = false; File[] files = tasksDirectory.listFiles((FileFilter) FileFilterUtils.directoryFileFilter()); List<Integer> numbers = new ArrayList<>(); for (File directory : files) { try { numbers.add(Integer.valueOf(directory.getName())); } catch (Throwable ignored) { } } numbers.sort(Comparator.<Integer>reverseOrder()); numbers = numbers.subList(0, Math.min(100, numbers.size())); for (int taskId : numbers) { File infoFile = new File(new File(tasksDirectory, String.valueOf(taskId)), "info.json"); if (!infoFile.exists()) { continue; } if (needComma) { output.write(",\n".getBytes()); } else { needComma = true; } try (FileInputStream fis = new FileInputStream(infoFile)) { IOUtils.copy(fis, output); } } output.write("]\n".getBytes()); } catch (IOException e) { throw Throwables.propagate(e); } }
void sortTransactionByDate() { List<Transaction> tr = new ArrayList<Transaction>(transactions.values()); tr.sort(Transaction.DateComparator); for (Transaction t : tr) { t.displayTransaction(); } }
void sortbyAccount() { List<Accounts> ac = new ArrayList<Accounts>(accounts.values()); ac.sort(Accounts.AccountComparator); for (Accounts a : ac) { a.dispaly(); } }
static void lambdaTest() { Runnable r = () -> System.out.print("hello lambda"); r.run(); List<String> list = Arrays.asList("t1", "t2", "t334", "t4", "t567"); list.parallelStream().filter(s -> s.length() == 2).forEach(System.out::println); list = Arrays.asList("1", "2", "3", "4", "5", "6", "7", "8", "9", "15", "17"); Map<String, Integer> integers = list.stream() .map(Integer::new) .filter(e -> e % 2 != 0) .distinct() .collect(Collectors.toMap(Object::toString, e -> e)); System.out.println(integers); Stream.generate(Math::random).limit(10).forEach(System.out::println); new Thread(() -> System.out.println("hello lambda")).start(); new Thread( () -> { System.out.println("hello lambda"); }) .start(); List<String> words = Lists.newArrayList("ren", "wang", "li", "zhao", "ma"); words.sort((w1, w2) -> Integer.compare((w1.length()), w2.length())); List<Integer> ints = Ints.asList(1, 2, 3, 4, 5); ints.sort(Integer::compare); // words.forEach(e -> System.out.print(e)); words.forEach(System.out::println); // words.stream().map(w -> w.length()); words.stream().map(String::length); // words.stream().map(w -> new StringBuilder(w)); words.stream().map(StringBuilder::new); Converter<String, Integer> converter; // (f) -> Integer.valueOf(f); converter = Integer::valueOf; Integer converted = converter.convert("123"); System.out.println(converted); String[] arrayStr = new String[] {"a", "ab", "abc", "abcd"}; Arrays.sort(arrayStr, (first, second) -> Integer.compare(first.length(), second.length())); }
/** Fetches available package versions using JSON API of PyPI. */ @NotNull private List<String> getPackageVersionsFromPyPI(@NotNull String packageName, boolean force) throws IOException { final PackageDetails details = refreshAndGetPackageDetailsFromPyPI(packageName, force); final List<String> result = details.getReleases(); result.sort(PackageVersionComparator.VERSION_COMPARATOR.reversed()); return Collections.unmodifiableList(result); }
static void collectionTest() { // removeIf Collection<String> c = new HashSet<>(); c.add("Content 1"); c.add("Content 2"); c.add("Content 3"); c.add("Content 4"); c.removeIf(s -> s.contains("2")); System.out.println("removeIf : " + c); /// 基本操作 List<Integer> list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); list.removeIf(a -> a % 3 == 0); System.out.println("a % 3 == 0 " + list); // OR 操作 Predicate<Integer> predicate2 = a -> a % 3 == 0; Predicate<Integer> predicate3 = a -> a % 5 == 0; list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); list.removeIf(predicate2.or(predicate3)); System.out.println("a % 3 == 0 or a % 5 == 0 " + list); // AND 操作 predicate2 = a -> a % 3 == 0; predicate3 = a -> a % 5 == 0; list = new ArrayList(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11)); list.removeIf(predicate2.and(predicate3)); System.out.println("a % 3 == 0 and a % 5 == 0 " + list); List<String> stringList = Arrays.asList("a", "b"); stringList.forEach(System.out::println); stringList = Arrays.asList("a", "b", "c"); stringList.replaceAll(String::toUpperCase); System.out.println(stringList); // [A, B, C] stringList = Arrays.asList("a", "b", "c"); stringList.sort(String::compareTo); Map<String, Integer> map = new HashMap<>(); map.put("A", 10); map.put("B", 20); map.put("C", 30); map.forEach((k, v) -> System.out.println("Item : " + k + " Count : " + v)); System.out.println(map.getOrDefault("D", 40)); // => 40 }
public List<String> testSorted(List<String> list) { List<String> result = new ArrayList<>(); for (String s : list) { result.add(s); } result.sort(null); return result.toArray(new String[0]); }
@Override public PagerResult<GeneratorInstance> search(GeneratorInstanceSearchRequest request) { Long userId = request.getUserId(); String name = StringUtils.hasText(request.getName()) ? request.getName() : null; List<GeneratorInstance> records = generatorInstanceRepository.filter( generatorInstance -> { if (generatorInstance.getIsDelete()) { return false; } if (name != null) { if (!generatorInstance.getName().contains(name)) { return false; } } if (userId != null) { if (!userId.equals(generatorInstance.getUser().getId())) { return false; } } return true; }); Integer page = request.getPage(); Integer pageSize = request.getPageSize(); Integer fromIndex = (page - 1) * pageSize; Integer toIndex = fromIndex + pageSize > records.size() ? records.size() : fromIndex + pageSize; List<GeneratorInstance> limitRecords = records.subList(fromIndex, toIndex); List<GeneratorInstance> result = new ArrayList<>(); for (GeneratorInstance g : limitRecords) { GeneratorInstance generatorInstance = new GeneratorInstance(); generatorInstance.setId(g.getId()); generatorInstance.setName(g.getName()); generatorInstance.setCreateDate(g.getCreateDate()); generatorInstance.setModifyDate(g.getModifyDate()); generatorInstance.setIsDelete(g.getIsDelete()); User userPersistence = userRepository.selectById(g.getUser().getId()); generatorInstance.setUser(userPersistence); Generator generatorPersistence = generatorRepository.selectById(g.getGenerator().getId()); if (generatorPersistence == null) { throw new AppException("生成器不存在"); } generatorInstance.setGenerator(generatorPersistence); generatorInstance.setDataModel(g.getDataModel()); generatorInstance.setVersion(g.getVersion()); result.add(generatorInstance); } String sortField = request.getSortField(); String sortDirection = request.getSortDirection(); if ("modifyDate".equals(sortField)) { if ("DESC".equalsIgnoreCase(sortDirection)) { result.sort( (g1, g2) -> (int) (g2.getModifyDate().getTime() - g1.getModifyDate().getTime())); } } return new PagerResult<>(result, (long) records.size()); }
@NotNull public static List<SymfonyInstallerVersion> getVersions(@NotNull String jsonContent) { JsonObject jsonObject = new JsonParser().parse(jsonContent).getAsJsonObject(); List<SymfonyInstallerVersion> symfonyInstallerVersions = new ArrayList<>(); // prevent adding duplicate version on alias names Set<String> aliasBranches = new HashSet<>(); // get alias version, in most common order for (String s : new String[] {"latest", "lts"}) { JsonElement asJsonObject = jsonObject.get(s); if (asJsonObject == null) { continue; } String asString = asJsonObject.getAsString(); aliasBranches.add(asString); symfonyInstallerVersions.add( new SymfonyInstallerVersion(s, String.format("%s (%s)", asString, s))); } List<SymfonyInstallerVersion> branches = new ArrayList<>(); Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entries) { if (!entry.getKey().matches("^\\d+\\.\\d+$")) { continue; } // "2.8.0-dev", "2.8.0-DEV" is not supported String asString = entry.getValue().getAsString(); if (asString.matches(".*[a-zA-Z].*") || aliasBranches.contains(asString)) { continue; } branches.add( new SymfonyInstallerVersion( asString, String.format("%s (%s)", entry.getKey(), asString))); } branches.sort(Comparator.comparing(SymfonyInstallerVersion::getVersion)); Collections.reverse(branches); symfonyInstallerVersions.addAll(branches); // we need reverse order for sorting them on version string List<SymfonyInstallerVersion> installableVersions = new ArrayList<>(); for (JsonElement installable : jsonObject.getAsJsonArray("installable")) { installableVersions.add(new SymfonyInstallerVersion(installable.getAsString())); } Collections.reverse(installableVersions); symfonyInstallerVersions.addAll(installableVersions); return symfonyInstallerVersions; }
void sortAccountByType() { List<Accounts> ac = new ArrayList<Accounts>(accounts.values()); ac.sort(Accounts.TypeComparator); ac.stream() .forEach( (a) -> { a.dispaly(); }); }
void sortAccountByCustomer() { List<Customer> cl = new ArrayList<Customer>(customers.values()); cl.sort(Customer.CustomerComparatorByName); for (Customer c : cl) { System.out.println("Customer Name: " + c.CustomerName); Accounts a = accounts.get(c.AccountId); a.dispaly(); } }
public static void main(String[] args) { // Methods in Comparator List<Person> people = new ArrayList<>(); people.sort( Comparator.comparing(Person::getLastName) .thenComparing(Person::getFirstName) .thenComparing( Person::getEmailAddress, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER))); // Old way of initializing ThreadLocal: ThreadLocal<List<String>> oldThreadLocalString = new ThreadLocal<List<String>>() { @Override public List<String> initialValue() { return new ArrayList<>(); } }; System.out.println(oldThreadLocalString.get()); // New way: ThreadLocal<List<String>> newThreadLocalString = ThreadLocal.withInitial(ArrayList::new); System.out.println(newThreadLocalString.get()); // Java Optional Optional<Integer> optional = new ArrayList<Integer>().stream().min(Integer::compareTo); System.out.println(optional); // Files can now return streams try { Stream stream = Files.list(Paths.get("c:\\temp\\")); stream = Files.lines(Paths.get("c:\\temp\\"), Charset.forName("UTF_32")); stream = Files.find(Paths.get("c:\\"), 5, (T, U) -> (T == U)); } catch (IOException e) { UncheckedIOException ex = new UncheckedIOException("cause", e); System.out.println(ex.getMessage()); } // Rejoice, for we finally have string joins! String joinExample = String.join(",", "a", "b", "c", "4", "E", "6"); System.out.println(joinExample); StringJoiner joiner = new StringJoiner("-"); joiner.add("abbie"); joiner.add("doobie"); System.out.println(joiner.toString()); }
@FXML private void initialize() { ObservableList<String> kunden = FXCollections.observableArrayList(KundeSession.getAllKundenNamen()); kunden.add(0, "Alle"); kundenChoiceBox.setItems(kunden); kundenChoiceBox.setValue("Alle"); String dm = now.getDayOfMonth() + "." + now.getMonthValue() + "."; day1Label.setText("1.1. - " + dm); day2Label.setText("1.1. - " + dm); List<Auftrag> auftraege = AuftragSession.getAllAuftraege(); auftraege.sort(Comparator.comparing(Auftrag::getErstellung)); LocalDate oldestAuftrag = auftraege.get(0).getErstellung(); ObservableList<Number> years = FXCollections.observableArrayList(); for (int i = now.getYear(); i >= oldestAuftrag.getYear(); i--) { years.add(i); } year1ChoiceBox.setItems(years); year1ChoiceBox.setValue(years.get(1)); year2ChoiceBox.setItems(years); year2ChoiceBox.setValue(years.get(0)); calculate(); pNrColumn.setCellValueFactory(cellData -> cellData.getValue().produktNr); bezColumn.setCellValueFactory(cellData -> cellData.getValue().bezeichnung); bildColumn.setCellValueFactory(cellData -> cellData.getValue().bild); bildColumn.setCellFactory(imageCellFactory); s1Column.setCellValueFactory(cellData -> cellData.getValue().stuckzahl1); u1Column.setCellValueFactory(cellData -> cellData.getValue().umsatz1); s2Column.setCellValueFactory(cellData -> cellData.getValue().stuckzahl2); u2Column.setCellValueFactory(cellData -> cellData.getValue().umsatz2); pInfoTable.setItems(dataShow); kundenChoiceBox.valueProperty().addListener(observable -> calculate()); year1ChoiceBox.valueProperty().addListener(observable -> calculate()); year2ChoiceBox.valueProperty().addListener(observable -> calculate()); }
private void initializeImplicitConstructor(SymbolResolver resolver) { List<? extends FormalParameter> inheritedParams = Collections.emptyList(); if (getBaseType().isPresent()) { List<InternalConstructorDefinition> constructors = getBaseType().get().asReferenceTypeUsage().getTypeDefinition().getConstructors(); if (constructors.size() != 1) { throw new UnsupportedOperationException(); } inheritedParams = constructors.get(0).getFormalParameters(); } List<FormalParameterNode> newParams = this.assignableProperties(resolver) .stream() .map( (p) -> new FormalParameterNode( p.getTypeUsage().copy(), p.getName(), p.getDefaultValue())) .collect(Collectors.toList()); List<FormalParameter> allParams = new LinkedList<>(); allParams.addAll(inheritedParams); allParams.addAll(newParams); allParams.sort( new Comparator<FormalParameter>() { @Override public int compare(FormalParameter o1, FormalParameter o2) { return Boolean.compare(o1.hasDefaultValue(), o2.hasDefaultValue()); } }); for (FormalParameter p : allParams) { // needed to solve symbols if (p.isNode()) { p.asNode().setParent(this); } } addConstructorWithParams(allParams, resolver); }
@NotNull private static List<String> parsePackageVersionsFromArchives(@NotNull String archivesUrl) throws IOException { return HttpRequests.request(archivesUrl) .userAgent(getUserAgent()) .connect( request -> { final List<String> versions = new ArrayList<>(); final Reader reader = request.getReader(); new ParserDelegator() .parse( reader, new HTMLEditorKit.ParserCallback() { HTML.Tag myTag; @Override public void handleStartTag(HTML.Tag tag, MutableAttributeSet set, int i) { myTag = tag; } @Override public void handleText(@NotNull char[] data, int pos) { if (myTag != null && "a".equals(myTag.toString())) { String packageVersion = String.valueOf(data); final String suffix = ".tar.gz"; if (!packageVersion.endsWith(suffix)) return; packageVersion = StringUtil.trimEnd(packageVersion, suffix); versions.add(splitNameVersion(packageVersion).second); } } }, true); versions.sort(PackageVersionComparator.VERSION_COMPARATOR.reversed()); return versions; }); }
public List<Player> getPlayerList() { List<Player> playerList = new LinkedList<>(getPlayers()); playerList.sort((a, b) -> a.getOrder() - b.getOrder()); return Collections.unmodifiableList(playerList); }
public static void main(String[] args) { // DBResourcesManager.initHibernate(); OffertaEvento of = new OffertaEvento(); of.setNome("ofevent"); of.setTipologia("Concerto"); of.setPrezzo(69); // of.setDataScadenza("21/08/2019"); of.setCittà("Roma"); Offerta offertaArray[] = {new OffertaEvento(), new OffertaPernotto(), new OffertaTrasporto()}; /* for(Offerta o : offertaArray) { System.out.println(o.getClass().getSimpleName() + "\n"); Method[] methods = o.getClass().getMethods(); for (Method m : methods) { int l = m.getName().length(); if (m.getName().substring(0, 3).equals("set") && !m.getName().substring(l - 2, l).equals("ID")) System.out.println(m.getName()); } }*/ /* OffertaBean object = new OffertaEventoBean(); String query = "from "+ object.getClass().getSimpleName() + " where "; System.out.println(object.getClass().getSimpleName() + "\n"); Method[] methods = object.getClass().getMethods(); for (Method m : methods) { int l = m.getName().length(); if (m.getName().substring(0, 3).equals("get") && !m.getName().substring(l - 2, l).equals("ID") && !m.getName().equals("getClass")) { String s = m.getName().substring(0,1).toLowerCase(); String attributeLower = s + m.getName().substring(1); query = query + attributeLower + " = "; } }*/ String città = "Roma"; String dataScadenza = "11/07/2009"; String nome = "Bubu"; String prezzo = "4"; String tipologia = "Museo"; String query = "from OffertaEvento offertaEvento"; query = query + " where "; if (città != null) query = query + "offertaEvento.città = '" + città + "' && "; if (dataScadenza != null) query = query + "offertaEvento.dataScadenza = '" + dataScadenza + "' && "; if (nome != null) query = query + "offertaEvento.nome = '" + nome + "' && "; if (prezzo != null) query = query + "offertaEvento.prezzo = '" + prezzo + "' && "; if (tipologia != null) query = query + "offertaEvento.tipologia = '" + tipologia + "'"; System.out.println(query); ArrayList<String> ls = new ArrayList<String>(); ls.add(città); ls.add(dataScadenza); ls.add(nome); ls.add(prezzo); ls.add(tipologia); System.out.println("\nNuova query\n"); if (!ls.isEmpty()) query.join(" where"); for (int i = 0; i < ls.size(); i++) { if (!ls.get(i).equals("") && i == 0) query.join(" && offertaEvento.città = '" + ls.get(i) + "'"); if (!ls.get(i).equals("") && i == 1) query.join(" && offertaEvento.dataScadenza = '" + ls.get(i) + "'"); if (!ls.get(i).equals("") && i == 2) query.join(" && offertaEvento.nome = '" + ls.get(i) + "'"); if (!ls.get(i).equals("") && i == 3) query.join(" && offertaEvento.prezzo = '" + ls.get(i) + "'"); if (!ls.get(i).equals("") && i == 4) query.join(" && offertaEvento.tipologia = '" + ls.get(i) + "'"); } System.out.println(query); Offerta o = new OffertaEvento(); List<Method> fields = Arrays.asList(o.getClass().getDeclaredMethods()); Class c = o.getClass().getSuperclass(); List<Method> superfields = Arrays.asList(c.getDeclaredMethods()); List<Method> allfields = new ArrayList<Method>(fields); allfields.addAll(superfields); allfields.sort( new Comparator<Method>() { public int compare(Method o1, Method o2) { return o1.getName().compareTo(o1.getName()); } }); /* for(Method f: allfields){ }*/ java.sql.Date date = Date.valueOf(LocalDate.now()); System.out.println(date); String datestring = date.toString(); System.out.println(datestring); Date data2 = Date.valueOf(datestring); System.out.println(data2); // OffertaEventoDAO.store(of); // System.out.println(((List<OffertaEvento>)DAOFactory.getDAOFactory(TipoOfferta.OffertaEvento).getOffertaDAO().getList()).size()); // DBResourcesManager.shutdown(); // OffertaDaoAnnotations.findAllOffertaEntitysA("offertaevento","Concerto"); }
// Does point to point routing with data from request public ProfileResponse getPlan(ProfileRequest request) { long startRouting = System.currentTimeMillis(); request.zoneId = transportNetwork.getTimeZone(); // Do the query and return result ProfileResponse profileResponse = new ProfileResponse(); ProfileOption option = new ProfileOption(); findDirectPaths(request, option); option.summary = option.generateSummary(); profileResponse.addOption(option); if (request.hasTransit()) { Map<LegMode, StreetRouter> accessRouter = new HashMap<>(request.accessModes.size()); Map<LegMode, StreetRouter> egressRouter = new HashMap<>(request.egressModes.size()); // This map saves which access mode was used to access specific stop in access mode TIntObjectMap<LegMode> stopModeAccessMap = new TIntObjectHashMap<>(); // This map saves which egress mode was used to access specific stop in egress mode TIntObjectMap<LegMode> stopModeEgressMap = new TIntObjectHashMap<>(); findAccessPaths(request, accessRouter); findEgressPaths(request, egressRouter); // fold access and egress times into single maps TIntIntMap accessTimes = combineMultimodalRoutingAccessTimes(accessRouter, stopModeAccessMap, request); TIntIntMap egressTimes = combineMultimodalRoutingAccessTimes(egressRouter, stopModeEgressMap, request); McRaptorSuboptimalPathProfileRouter router = new McRaptorSuboptimalPathProfileRouter( transportNetwork, request, accessTimes, egressTimes); List<PathWithTimes> usefullpathList = new ArrayList<>(); // getPaths actually returns a set, which is important so that things are deduplicated. // However we need a list // so we can sort it below. usefullpathList.addAll(router.getPaths()); // This sort is necessary only for text debug output so it will be disabled when it is // finished /** * Orders first no transfers then one transfers 2 etc - then orders according to first trip: - * board stop - alight stop - alight time - same for one transfer trip */ usefullpathList.sort( (o1, o2) -> { int c; c = Integer.compare(o1.patterns.length, o2.patterns.length); if (c == 0) { c = Integer.compare(o1.boardStops[0], o2.boardStops[0]); } if (c == 0) { c = Integer.compare(o1.alightStops[0], o2.alightStops[0]); } if (c == 0) { c = Integer.compare(o1.alightTimes[0], o2.alightTimes[0]); } if (c == 0 && o1.patterns.length == 2) { c = Integer.compare(o1.boardStops[1], o2.boardStops[1]); if (c == 0) { c = Integer.compare(o1.alightStops[1], o2.alightStops[1]); } if (c == 0) { c = Integer.compare(o1.alightTimes[1], o2.alightTimes[1]); } } return c; }); LOG.info("Usefull paths:{}", usefullpathList.size()); int seen_paths = 0; int boardStop = -1, alightStop = -1; for (PathWithTimes path : usefullpathList) { profileResponse.addTransitPath( accessRouter, egressRouter, stopModeAccessMap, stopModeEgressMap, path, transportNetwork, request.getFromTimeDateZD()); // LOG.info("Num patterns:{}", path.patterns.length); // ProfileOption transit_option = new ProfileOption(); /*if (path.patterns.length == 1) { continue; }*/ /*if (seen_paths > 20) { break; }*/ if (LOG.isDebugEnabled()) { LOG.debug(" "); for (int i = 0; i < path.patterns.length; i++) { // TransitSegment transitSegment = new TransitSegment(transportNetwork.transitLayer, // path.boardStops[i], path.alightStops[i], path.patterns[i]); if (!(((boardStop == path.boardStops[i] && alightStop == path.alightStops[i])))) { LOG.debug( " BoardStop: {} pattern: {} allightStop: {}", path.boardStops[i], path.patterns[i], path.alightStops[i]); } TripPattern pattern = transportNetwork.transitLayer.tripPatterns.get(path.patterns[i]); if (pattern.routeIndex >= 0) { RouteInfo routeInfo = transportNetwork.transitLayer.routes.get(pattern.routeIndex); LOG.debug( " Pattern:{} on route:{} ({}) with {} stops", path.patterns[i], routeInfo.route_long_name, routeInfo.route_short_name, pattern.stops.length); } LOG.debug( " {}->{} ({}:{})", transportNetwork.transitLayer.stopNames.get(path.boardStops[i]), transportNetwork.transitLayer.stopNames.get(path.alightStops[i]), path.alightTimes[i] / 3600, path.alightTimes[i] % 3600 / 60); // transit_option.addTransit(transitSegment); } boardStop = path.boardStops[0]; alightStop = path.alightStops[0]; } seen_paths++; } profileResponse.generateStreetTransfers(transportNetwork, request); } LOG.info("Returned {} options", profileResponse.getOptions().size()); LOG.info("Took {} ms", System.currentTimeMillis() - startRouting); return profileResponse; }
/** * Puts the given lesson plans into classrooms based on the distance the member fo staff will have * to travel between each lesson. * * @param lessonPlans The lessonPlans to be put into classrooms. * @param classrooms The classrooms to put lessons plans into. * @param distances The distances between the classrooms. * @return The list of lessonPlans after they have been put into classrooms. */ private boolean putLessonPlansIntoClassrooms( List<LessonPlan> lessonPlans, List<Classroom> classrooms, List<Distance> distances) { // Create a week of periods for this subject List<List<LessonPlan>> week = new ArrayList<>(); for (int i = 0; i < 5; i++) { week.add(new ArrayList<>()); } lessonPlans .stream() .forEach(lessonPlan -> week.get(lessonPlan.period.day.id - 1).add(lessonPlan)); List<Period> periods; // Iterate through each day for (int dayNo = 0; dayNo < week.size(); dayNo++) { // Get the periods of this day try { periods = daoManager .getPeriodDao() .getAllByDay( daoManager .getDayDao() .getById(dayNo + 1) .orElseThrow( () -> new IllegalStateException("Failed to find periods in a day"))); // The above exception should never be thrown periods.sort((o1, o2) -> o1.startTime.getHour() - o2.startTime.getHour()); } catch (DataAccessException e) { DataExceptionHandler.handleJavaFx(e, "period", false); return false; } catch (DataConnectionException e) { DataExceptionHandler.handleJavaFx(e, null, true); return false; } // Get this days lessons and randomly allocate the first period List<LessonPlan> day = week.get(dayNo); List<LessonPlan> firstPeriod = new ArrayList<>(); day.forEach( lessonPlan -> { if (lessonPlan.period.startTime.equals(LocalTime.of(9, 10))) { firstPeriod.add(lessonPlan); } }); classrooms .stream() .forEach( classroom -> { for (LessonPlan lessonPlan : firstPeriod) { if (lessonPlan.classroom.id == -1) { lessonPlan.classroom = classroom; break; } } }); // Store the first period in the timetabled list firstPeriod.forEach( lessonPlan -> { int index = lessonPlans.indexOf(lessonPlan); lessonPlans.set(index, lessonPlan); }); List<LessonPlan> previousPeriod = new ArrayList<>(firstPeriod); // Iterate through the other periods for (int periodNo = 1; periodNo < 5; periodNo++) { List<LessonPlan> period = new ArrayList<>(); for (LessonPlan lessonPlan : day) { if (lessonPlan.period.equals(periods.get(periodNo - 1))) { period.add(lessonPlan); } } // Timetable lessons where the staff member had a lesson previously for (LessonPlan lessonPlan : period) { Staff staff = lessonPlan.staff; Optional<LessonPlan> previousLesson = previousPeriod.stream().filter(lesson -> lesson.staff.equals(staff)).findFirst(); if (previousLesson.isPresent()) { Optional<LessonPlan> planOptional = period .stream() .filter(plan -> plan.classroom.equals(previousLesson.get().classroom)) .findFirst(); if (planOptional.isPresent()) { List<Distance> availableRooms = distances .stream() .filter( distance -> distance.startRoom.equals(planOptional.get().classroom) || distance.endRoom.equals(planOptional.get().classroom)) .collect(Collectors.toList()); availableRooms.removeIf( distance -> { boolean remove = false; for (LessonPlan plan : period) { if (plan.classroom.equals(distance.startRoom) || plan.classroom.equals(distance.endRoom)) { remove = true; } } return remove; }); availableRooms.sort((o1, o2) -> o1.distance - o2.distance); Distance nextTrip = availableRooms.get(0); if (nextTrip.startRoom.equals(planOptional.get().classroom)) { lessonPlan.classroom = nextTrip.endRoom; } else if (nextTrip.endRoom.equals(planOptional.get().classroom)) { lessonPlan.classroom = nextTrip.startRoom; } else { assert false : "The new classroom should be one from the shortest distance!"; } } else { lessonPlan.classroom = previousLesson.get().classroom; } } } // Timetable the remaining lessons randomly for (LessonPlan lessonPlan : period) { if (lessonPlan.classroom != null) { List<Classroom> availableRooms = new ArrayList<>(); availableRooms.addAll(classrooms); availableRooms.removeIf( classroom -> { boolean remove = false; for (LessonPlan plan : period) { if (classroom.equals(plan.classroom)) { remove = true; } } return remove; }); lessonPlan.classroom = availableRooms.get(0); } } previousPeriod = period; } } return true; }