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:Main.java

/**
 * Methode permettant de splitter une liste en un certain nombre de sous-listes
 * @param list   Liste originale//ww  w. ja v a 2s .  c  o  m
 * @param subListNumber   Nombre de sous-listes souhaitees
 * @return   Liste de sous-liste splittee
 */
public static <T> List<List<T>> splitList(List<T> list, int subListNumber) {

    // Liste a retourner
    List<List<T>> splitted = new ArrayList<List<T>>();

    // Si la liste est vide
    if (list == null || list.size() == 0)
        return splitted;

    // Taille de la liste
    int listSize = list.size();

    // Nombre d'elements de la liste
    int subSize = Math.max(listSize / (subListNumber - 1), 1);

    // Parcours de la liste a splitter
    for (int i = 0; i < listSize; i += subSize) {

        // Ajout de la sous-liste
        splitted.add(new ArrayList<T>(list.subList(i, Math.min(listSize, i + subSize))));
    }

    // On retourne la liste des sous-listes
    return splitted;
}

From source file:com.mmj.app.common.authority.AuthorityHelper.java

/**
 * @param role??, 0101001001000000000/*from   w  w  w  . ja  v  a2  s .  c om*/
 * @return ??, 1,3,6,11,20
 */
public static String createRightStr(String role) {
    if (StringUtils.isEmpty(role)) {
        return StringUtils.EMPTY;
    }
    StringBuffer sb = new StringBuffer();
    List<Right> rightList = (List<Right>) createRightList(role);
    if (rightList == null || rightList.size() == 0) {
        return StringUtils.EMPTY;
    }
    if (rightList.size() == 1) {
        sb.append(rightList.get(0).getIndex());
        return sb.toString();
    }
    if (rightList.size() == 2) {
        sb.append(rightList.get(0).getIndex());
        sb.append(",");
        sb.append(rightList.get(1).getIndex());
        return sb.toString();
    }
    for (Right right : rightList.subList(0, rightList.size() - 2)) {
        sb.append(right.getIndex());
        sb.append(",");
    }
    sb.append(rightList.get(rightList.size() - 1).getIndex());
    return sb.toString();
}

From source file:com.jsonstore.util.JSONStoreUtil.java

public static List<List<Integer>> splitListIntoChunks(List<Integer> arr, int chunk_size) {
    List<List<Integer>> list = new LinkedList<List<Integer>>();
    int start = 0;
    int count = arr.size();
    if (count <= chunk_size) {
        list.add(arr);//  w  w  w . ja va 2s . c o m
    } else {
        while (count > 0) {
            int numToCopy = Math.min(chunk_size, arr.size() - start);
            list.add(arr.subList(start, start + numToCopy));
            start += chunk_size;
            count -= chunk_size;
        }
    }

    return list;

}

From source file:com.floragunn.searchguard.util.SecurityUtil.java

public static InetAddress getProxyResolvedHostAddressFromRequest(final RestRequest request,
        final Settings settings) throws UnknownHostException {

    // this.logger.debug(request.getClass().toString());

    final String oaddr = ((InetSocketAddress) request.getRemoteAddress()).getHostString();
    // this.logger.debug("original hostname: " + addr);

    String raddr = oaddr;//from w  w w . j a  v  a  2 s .c  om

    if (oaddr == null || oaddr.isEmpty()) {
        throw new UnknownHostException("Original host is <null> or <empty>");
    }

    final InetAddress iaddr = InetAddress.getByName(oaddr);

    final String xForwardedForHeader = settings.get(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_HEADER,
            "X-Forwarded-For");

    if (xForwardedForHeader != null && !xForwardedForHeader.isEmpty()) {

        final String xForwardedForValue = request.header(xForwardedForHeader);

        //logger.trace("xForwardedForHeader is " + xForwardedForHeader + ":" + xForwardedForValue);

        final String[] xForwardedTrustedProxies = settings
                .getAsArray(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_TRUSTEDPROXIES);

        final boolean xForwardedEnforce = settings
                .getAsBoolean(ConfigConstants.SEARCHGUARD_HTTP_XFORWARDEDFOR_ENFORCE, false);

        if (xForwardedForValue != null && !xForwardedForValue.isEmpty()) {
            final List<String> addresses = Arrays.asList(xForwardedForValue.replace(" ", "").split(","));
            final List<String> proxiesPassed = new ArrayList<String>(addresses.subList(1, addresses.size()));

            if (xForwardedTrustedProxies.length == 0) {
                throw new UnknownHostException("No trusted proxies");
            }

            proxiesPassed.removeAll(Arrays.asList(xForwardedTrustedProxies));

            //logger.debug(proxiesPassed.size() + "/" + proxiesPassed);

            if (proxiesPassed.size() == 0
                    && (Arrays.asList(xForwardedTrustedProxies).contains(oaddr) || iaddr.isLoopbackAddress())) {

                raddr = addresses.get(0).trim();

            } else {
                throw new UnknownHostException("Not all proxies are trusted");
            }

        } else {
            if (xForwardedEnforce) {
                throw new UnknownHostException("Forward header enforced but not present");
            }
        }

    }

    if (raddr == null || raddr.isEmpty()) {
        throw new UnknownHostException("Host is <null> or <empty>");
    }

    if (raddr.equals(oaddr)) {
        return iaddr;
    } else {
        // if null or "" then loopback is returned
        return InetAddress.getByName(raddr);
    }

}

From source file:com.petalmd.armor.util.SecurityUtil.java

public static InetAddress getProxyResolvedHostAddressFromRequest(final RestRequest request,
        final Settings settings) throws UnknownHostException {

    // this.logger.debug(request.getClass().toString());

    final String oaddr = ((InetSocketAddress) request.getRemoteAddress()).getHostString();
    // this.logger.debug("original hostname: " + addr);

    String raddr = oaddr;/* w  w w .jav  a2 s . com*/

    if (oaddr == null || oaddr.isEmpty()) {
        throw new UnknownHostException("Original host is <null> or <empty>");
    }

    final InetAddress iaddr = InetAddress.getByName(oaddr);

    final String xForwardedForHeader = settings.get(ConfigConstants.ARMOR_HTTP_XFORWARDEDFOR_HEADER,
            "X-Forwarded-For");

    if (xForwardedForHeader != null && !xForwardedForHeader.isEmpty()) {

        final String xForwardedForValue = request.header(xForwardedForHeader);

        //logger.trace("xForwardedForHeader is " + xForwardedForHeader + ":" + xForwardedForValue);

        final String[] xForwardedTrustedProxies = settings
                .getAsArray(ConfigConstants.ARMOR_HTTP_XFORWARDEDFOR_TRUSTEDPROXIES);

        final boolean xForwardedEnforce = settings
                .getAsBoolean(ConfigConstants.ARMOR_HTTP_XFORWARDEDFOR_ENFORCE, false);

        if (xForwardedForValue != null && !xForwardedForValue.isEmpty()) {
            final List<String> addresses = Arrays.asList(xForwardedForValue.replace(" ", "").split(","));
            final List<String> proxiesPassed = new ArrayList<String>(addresses.subList(1, addresses.size()));

            if (xForwardedTrustedProxies.length == 0) {
                throw new UnknownHostException("No trusted proxies");
            }

            proxiesPassed.removeAll(Arrays.asList(xForwardedTrustedProxies));

            //logger.debug(proxiesPassed.size() + "/" + proxiesPassed);

            if (proxiesPassed.size() == 0
                    && (Arrays.asList(xForwardedTrustedProxies).contains(oaddr) || iaddr.isLoopbackAddress())) {

                raddr = addresses.get(0).trim();

            } else {
                throw new UnknownHostException("Not all proxies are trusted");
            }

        } else {
            if (xForwardedEnforce) {
                throw new UnknownHostException("Forward header enforced but not present");
            }
        }

    }

    if (raddr == null || raddr.isEmpty()) {
        throw new UnknownHostException("Host is <null> or <empty>");
    }

    if (raddr.equals(oaddr)) {
        return iaddr;
    } else {
        // if null or "" then loopback is returned
        return InetAddress.getByName(raddr);
    }

}

From source file:Main.java

@SuppressWarnings("hiding")
public static <T> List<List<T>> seperateList(List<T> list) {
    if (list == null) {
        throw new IllegalArgumentException("list should not be null");
    }/*from  w w w  .ja v a  2s. co m*/
    List<List<T>> ret = new ArrayList<List<T>>();

    if (list.size() <= MAX_FRAGEMENT_SIZE) {
        ret.add(list);
    } else {
        int fragementCount = list.size() / MAX_FRAGEMENT_SIZE + 1;

        for (int i = 0; i < fragementCount; i++) {
            int start = i * MAX_FRAGEMENT_SIZE;
            int end = start + MAX_FRAGEMENT_SIZE;

            if (end > list.size()) {
                end = list.size();
            }

            List<T> subList = list.subList(start, end);
            ret.add(subList);
        }

    }

    return ret;
}

From source file:wiki.doc.DocResource.java

public static List<DocId> getAllLinking(List<DocId> docs, DbConnector dbc) {
    if (docs.size() == 0) {
        return new ArrayList<>(0);
    } else if (docs.size() <= 30000) {
        String inList = getParamList(docs.size());
        String sql = "SELECT pages.id FROM pages " + "INNER JOIN links ON links.fromPage = pages.id "
                + "WHERE links.toPage IN " + inList;
        Object[] ids = docs.stream().map((doc) -> doc.id).toArray();

        return dbc.jdbcTemplate.query(sql, ids, docIdMapper);
    } else {/*from  ww w  .j a  v  a  2s  . c o  m*/
        List<DocId> first = getAllLinking(docs.subList(0, 30000), dbc);
        first.addAll(getAllLinking(docs.subList(30000, docs.size()), dbc));
        return first;
    }
}

From source file:wiki.doc.DocResource.java

public static List<DocId> getAllLinkedDocs(List<DocId> docs, DbConnector dbc) {
    if (docs.size() == 0) {
        return new ArrayList<>(0);
    } else if (docs.size() <= 30000) {
        String inList = getParamList(docs.size());
        String sql = "SELECT pages.id FROM pages " + "INNER JOIN links ON links.toPage = pages.id "
                + "WHERE links.fromPage IN " + inList;
        Object[] ids = docs.stream().map((doc) -> doc.id).toArray();

        return dbc.jdbcTemplate.query(sql, ids, docIdMapper);
    } else {//  w  w w . j a  v  a2 s .  c om
        List<DocId> first = getAllLinkedDocs(docs.subList(0, 30000), dbc);
        first.addAll(getAllLinkedDocs(docs.subList(30000, docs.size()), dbc));
        return first;
    }
}

From source file:fi.luontola.cqrshotel.framework.EventStoreContract.java

private static void assertAtomicBatches(int batchSize, List<Event> events) {
    if (events.size() % batchSize != 0) {
        throw new AssertionError(
                "incomplete batches found: " + events.size() + " events but " + batchSize + " batch size");
    }//w w w  .  j  a v a  2  s .co m
    List<List<Event>> batches = new ArrayList<>();
    for (int i = 0; i < events.size() / batchSize; i++) {
        int start = i * batchSize;
        batches.add(events.subList(start, start + batchSize));
    }
    for (List<Event> batch : batches) {
        DummyEvent sample = (DummyEvent) batch.get(0);
        String prefix = sample.message.substring(0, sample.message.indexOf('.'));
        try {
            for (int i = 0; i < batch.size(); i++) {
                DummyEvent event = (DummyEvent) batch.get(i);
                assertThat(event.message, is(prefix + "." + i));
            }
        } catch (AssertionError e) {
            throw new AssertionError("non-atomic batch found: " + batch, e);
        }
    }
}

From source file:com.fiveamsolutions.nci.commons.util.HibernateHelper.java

/**
 * Break up a list of items into separate in clauses, to avoid limits imposed by databases or by Hibernate bug
 * http://opensource.atlassian.com/projects/hibernate/browse/HHH-2166.
 * @param items list of items to include in the in clause
 * @param columnName name of column to match against the list
 * @param blocks empty Map of HQL param name to param list of values to be set in the HQL query - it will be
 *               populated by the method
 * @return full HQL "in" clause, of the form: " columnName in (:block1) or ... or columnName in (:blockN)"
 *//*w w w. j  a v a  2 s. co  m*/
public static String buildInClause(List<? extends Serializable> items, String columnName,
        Map<String, List<? extends Serializable>> blocks) {
    StringBuffer inClause = new StringBuffer();
    for (int i = 0; i < items.size(); i += MAX_IN_CLAUSE_LENGTH) {
        List<? extends Serializable> block = items.subList(i, Math.min(items.size(), i + MAX_IN_CLAUSE_LENGTH));
        String paramName = "block" + i / MAX_IN_CLAUSE_LENGTH;
        if (inClause.length() > 0) {
            inClause.append(" or");
        }
        inClause.append(" " + columnName + " in (:" + paramName + ")");
        blocks.put(paramName, block);
    }
    return inClause.toString();
}