Example usage for java.util List subList

List of usage examples for java.util List subList

Introduction

In this page you can find the example usage for java.util List subList.

Prototype

List<E> subList(int fromIndex, int toIndex);

Source Link

Document

Returns a view of the portion of this list between the specified fromIndex , inclusive, and toIndex , exclusive.

Usage

From source file:se.uu.it.cs.recsys.service.resource.impl.RecommendationGenerator.java

private Set<List<Course>> doRetry(List<Integer> inferredIdSet) {

    Set<List<Course>> solution = new HashSet<>();

    final int step = 10;
    int i = step;

    while (i < inferredIdSet.size()) {
        LOGGER.info("Retrying time {}", i / step);

        List<Integer> retryCandidates = inferredIdSet.subList(i - step, i);

        this.constraintPref.getInterestedCourseIdCollection().addAll(retryCandidates);

        solution = this.constraintSolver.getSolution(this.constraintPref);

        if (!solution.isEmpty()) {
            return solution;
        }/* w w w  .j  a  v a 2s . c o  m*/

        i = i + step;
    }

    if (inferredIdSet.size() % step != 0) {
        LOGGER.info("Retrying time {}", i / step);

        List<Integer> retryCandidates;

        if (i > inferredIdSet.size()) {
            retryCandidates = inferredIdSet.subList(i - step, inferredIdSet.size());
        } else {
            retryCandidates = inferredIdSet;
        }

        this.constraintPref.getInterestedCourseIdCollection().addAll(retryCandidates);

        solution = this.constraintSolver.getSolution(this.constraintPref);
    }

    return solution;
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.publico.ShowDegreeSiteAction.java

private void prepareInfo(HttpServletRequest request) throws FenixActionException {
    // inEnglish/*from w  ww  .j av  a  2 s .  c o  m*/
    Boolean inEnglish = FenixContextDispatchAction.getFromRequestBoolean("inEnglish", request);
    if (inEnglish == null) {
        inEnglish = getLocale(request).getLanguage().equals(Locale.ENGLISH.getLanguage());
    }
    request.setAttribute("inEnglish", inEnglish);

    // degree
    Degree degree = getDegree(request);
    if (degree == null) {
        throw new FenixActionException();
    }
    request.setAttribute("degreeID", degree.getExternalId());
    request.setAttribute("degree", degree);

    Unit unit = degree.getUnit();
    if (unit != null) {
        AnnouncementBoard board = null;
        for (AnnouncementBoard unitBoard : unit.getBoardsSet()) {
            if (unitBoard.isPublicToRead()) {
                board = unitBoard;
                break;
            }
        }

        if (board != null) {
            List<Announcement> announcements = board.getActiveAnnouncements();
            announcements = announcements.subList(0, Math.min(announcements.size(), ANNOUNCEMENTS_NUMBER));
            request.setAttribute("announcements", announcements);
        }
    }

    // execution year
    ExecutionYear executionYearToShow = getExecutionYearToShow(request, degree);
    request.setAttribute("executionYear", executionYearToShow);

    // info
    getInfoToShow(request, degree, executionYearToShow);
}

From source file:com.offbynull.peernetic.playground.chorddht.model.SuccessorTable.java

/**
 * Updates this successor table so that the immediate successor is {@code successor} and the successors after it are {@code table}. If
 * {@code table} contains the base pointer in it, all pointers including and after the base pointer won't be added. If {@code table}'s
 * size exceeds the number of bits in base pointer's id, it'll be trimmed so that it doesn't exceed. The pointers in {@code table} must
 * be sorted. The point at which {@code table} loops around our base id is the point that it'll be trimmed.
 * @param successor immediate successor/*from   w w  w.  j a  va  2 s. com*/
 * @param table successors after {@code successor}
 * @throws NullPointerException if any arguments are {@code null} or contain {@code null}
 * @throws IllegalArgumentException if {@code successor}'s id has a different limit bit size than the base pointer's id, or if the ids
 * of any of the pointers in {@code table} have a different limit bit size than the base pointer's id
 */
public void update(Pointer successor, List<Pointer> table) {
    Validate.notNull(successor);
    Validate.noNullElements(table);

    Id baseId = basePtr.getId();
    Id successorId = successor.getId();

    Validate.isTrue(IdUtils.getBitLength(successorId) == limit);

    if (table.size() > limit) {
        table = table.subList(0, limit);
    }

    Id lastId = successor.getId();
    int lastTableIdx = -1;
    int idx = 0;
    for (Pointer ptrSuccessor : table) {
        Id ptrSuccessorId = ptrSuccessor.getId();

        Validate.isTrue(IdUtils.getBitLength(ptrSuccessorId) == limit);

        if (baseId.equals(ptrSuccessorId)) {
            lastTableIdx = idx;
            break;
        }

        if (Id.comparePosition(baseId, ptrSuccessorId, lastId) <= 0) {
            lastTableIdx = idx;
            break;
        }

        lastId = ptrSuccessor.getId();

        idx++;
    }

    if (lastTableIdx != -1) {
        table = table.subList(0, lastTableIdx);
    }

    int len = table.size() + 1;
    ArrayDeque<Pointer> newTable = new ArrayDeque<>(len);

    newTable.add(successor);
    table.forEach(x -> {
        Id id = x.getId();
        if (id.equals(baseId)) {
            newTable.add(new InternalPointer(id)); // if referencing self, use internalpointer
        } else {
            newTable.add(x);
        }
    });

    this.table = newTable;
}

From source file:com.xtructure.xneat.genetics.UTestGeneMap.java

public void removeAllBehavesAsExpected() {
    NodeGene node0 = new NodeGeneImpl(0, NodeType.INPUT, NODE_CONFIGURATION);
    NodeGene node1 = new NodeGeneImpl(1, NodeType.OUTPUT, NODE_CONFIGURATION);
    LinkGene link0 = new LinkGeneImpl(0, node0.getId(), node1.getId(), LINK_CONFIGURATION);
    GeneMap geneMap = new GeneMap(//
            Arrays.asList(node0, node1), //
            Arrays.asList(link0));
    int i = RandomUtil.nextInteger(geneMap.size());
    List<Gene> list = RandomUtil.shuffle(geneMap);
    List<Gene> subList = list.subList(0, i);
    list = list.subList(i, list.size());
    for (Gene gene : list) {
        assertThat("", //
                geneMap, containsElement(gene));
    }// ww w.ja  va 2  s . co m
    for (Gene gene : subList) {
        assertThat("", //
                geneMap, containsElement(gene));
    }
    geneMap.removeAll(subList);
    for (Gene gene : list) {
        assertThat("", //
                geneMap, containsElement(gene));
    }
    for (Gene gene : subList) {
        assertThat("", //
                geneMap, not(containsElement(gene)));
    }
}

From source file:com.xtructure.xneat.genetics.UTestGeneMap.java

public void retainAllBehavesAsExpected() {
    NodeGene node0 = new NodeGeneImpl(0, NodeType.INPUT, NODE_CONFIGURATION);
    NodeGene node1 = new NodeGeneImpl(1, NodeType.OUTPUT, NODE_CONFIGURATION);
    LinkGene link0 = new LinkGeneImpl(0, node0.getId(), node1.getId(), LINK_CONFIGURATION);
    GeneMap geneMap = new GeneMap(//
            Arrays.asList(node0, node1), //
            Arrays.asList(link0));
    int i = RandomUtil.nextInteger(geneMap.size());
    List<Gene> list = RandomUtil.shuffle(geneMap);
    List<Gene> subList = list.subList(0, i);
    list = list.subList(i, list.size());
    for (Gene gene : list) {
        assertThat("", //
                geneMap, containsElement(gene));
    }/*from  ww w . j  av  a  2 s. c  om*/
    for (Gene gene : subList) {
        assertThat("", //
                geneMap, containsElement(gene));
    }
    geneMap.retainAll(subList);
    for (Gene gene : list) {
        assertThat("", //
                geneMap, not(containsElement(gene)));
    }
    for (Gene gene : subList) {
        assertThat("", //
                geneMap, containsElement(gene));
    }
}

From source file:edu.udo.scaffoldhunter.model.clustering.evaluation.FileSaverMetaModule.java

@Override
public Collection<EvaluationResult> run(List<EvaluationMetaModule> metaModules, EvaluationModule module) {
    // reset separate file counter
    count = 0;/* w  w  w. j  av  a 2  s . c  o  m*/

    if (metaModules.isEmpty()) {
        return run(module);
    } else {
        EvaluationMetaModule metaModule = metaModules.iterator().next();
        List<EvaluationMetaModule> metaModulesRest = metaModules.subList(1, metaModules.size());

        Collection<EvaluationResult> results = metaModule.run(metaModulesRest, module);
        save(results);
        return results;
    }
}

From source file:com.xebia.devradar.Timeline.java

public void update(Collection<Event> workspaceEvents) {

    List<Event> workspaceSortedEvents = new ArrayList<Event>(workspaceEvents);
    Collections.sort(workspaceSortedEvents, Collections.reverseOrder(new Comparator<Event>() {
        @Override/*from ww w  .ja  v a2s  .c  o m*/
        public int compare(Event o1, Event o2) {
            return new CompareToBuilder().append(o1.timestamp, o2.timestamp).toComparison();
        }
    }));

    if (workspaceSortedEvents.size() < MAX_SIZE) {
        this.events = workspaceSortedEvents;
    } else {
        this.events = workspaceSortedEvents.subList(0, MAX_SIZE);
    }
}

From source file:org.kordamp.javatrove.example04.FunctionalTest.java

@Test
public void _02_cancel_path() throws Exception {
    // given:/*from   ww w.j a v a2 s. c  om*/
    String nextUrl = "/organizations/1/repos?page=2";
    List<Repository> repositories = createSampleRepositories();
    stubFor(get(urlEqualTo("/orgs/" + ORGANIZATION + "/repos"))
            .willReturn(aResponse().withFixedDelay(200).withStatus(200).withHeader("Content-Type", "text/json")
                    .withHeader("Link", "<http://localhost:8080" + nextUrl + ">; rel=\"next\"")
                    .withBody(repositoriesAsJSON(repositories.subList(0, 5), objectMapper))));
    stubFor(get(urlEqualTo(nextUrl))
            .willReturn(aResponse().withFixedDelay(200).withStatus(200).withHeader("Content-Type", "text/json")
                    .withBody(repositoriesAsJSON(repositories.subList(5, 10), objectMapper))));

    // when:
    testfx.clickOn("#organization").eraseText(ORGANIZATION.length()).write(ORGANIZATION);
    testfx.clickOn("#loadButton");
    testfx.clickOn("#cancelButton");

    // wait
    Button loadButton = testfx.lookup("#loadButton").query();
    new WaitUntilSupport().waitUntil(loadButton, isEnabled(), 2);

    // then:
    verifyThat("#total", hasText("5"));
    verifyThat("#repositories", hasItems(5));
}

From source file:com.hp.mqm.atrf.alm.services.AlmEntityService.java

public List<AlmEntity> getEntitiesByIds(String collectionName, Set<String> ids, Collection<String> fields) {
    List<String> list = new ArrayList<>(ids);
    List<AlmEntity> allEntities = new ArrayList<>();
    for (int i = 0; i < list.size(); i = i + PAGE_SIZE_BY_ID) {
        int maxIndex = Math.min(i + PAGE_SIZE_BY_ID, list.size());
        List<String> subList = list.subList(i, maxIndex);
        AlmQueryBuilder qb = AlmQueryBuilder.create().addQueryCondition("id", StringUtils.join(subList, " OR "))
                .addSelectedFields(fields);
        AlmEntityCollection coll = getEntities(collectionName, qb);
        allEntities.addAll(coll.getEntities());
    }/*from   w  w  w.  j  a va 2s  .co m*/

    return allEntities;
}

From source file:net.monofraps.gradlecurse.tasks.ObtainGameVersionsTask.java

@TaskAction
public void obtainGameVersions() {
    final String responseString;

    try {//from w  w  w. j a va 2  s  .c o  m
        final HttpGet httpGet = new HttpGet(
                ((CurseDeploy) getProject().getExtensions().getByName("curseDeploy")).getBaseUrl()
                        + "/game-versions.json");
        getLogger().info("Obtaining game versions from " + httpGet.getURI().toString());

        final HttpClient httpClient = new DefaultHttpClient();
        final HttpResponse httpResponse = httpClient.execute(httpGet);
        final BufferedReader responseReader = new BufferedReader(
                new InputStreamReader(httpResponse.getEntity().getContent()));

        final StringBuilder response = new StringBuilder();
        String line;
        while ((line = responseReader.readLine()) != null) {
            response.append(line);
        }

        responseString = response.toString();
    } catch (IOException e) {
        e.printStackTrace();
        return;
    }

    final JsonElement response = (new JsonParser()).parse(responseString);
    final JsonObject versionAssList = response.getAsJsonObject();
    final List<GameVersion> gameVersions = new ArrayList<GameVersion>();

    for (final Map.Entry<String, JsonElement> versionObject : versionAssList.entrySet()) {
        gameVersions.add(new GameVersion(versionObject.getKey(), versionObject.getValue().getAsJsonObject()));
    }
    Collections.sort(gameVersions);

    for (final GameVersion gameVersion : (numVersionsToDisplay == -1) ? gameVersions
            : gameVersions.subList(gameVersions.size() - 3, gameVersions.size())) {

        getLogger().lifecycle(String.format("Version %s, released on %s", gameVersion.getVersionNumber(),
                gameVersion.getReleaseDate()));
        getLogger().lifecycle(String.format("\tName: %s", gameVersion.getName()));
        getLogger().lifecycle(String.format("\tIsDevelopment: %b", gameVersion.isDevelopment()));
        getLogger().lifecycle(String.format("\tBreaksCompatibility: %b", gameVersion.isBreaksCompatibility()));
    }
}