Example usage for java.util NavigableSet pollFirst

List of usage examples for java.util NavigableSet pollFirst

Introduction

In this page you can find the example usage for java.util NavigableSet pollFirst.

Prototype

E pollFirst();

Source Link

Document

Retrieves and removes the first (lowest) element, or returns null if this set is empty.

Usage

From source file:Main.java

public static void main(String[] args) {
    NavigableSet<Integer> ns = new TreeSet<>();
    ns.add(0);/*from w w  w.ja  v a 2 s. c  o m*/
    ns.add(1);
    ns.add(2);
    ns.add(3);
    ns.add(4);
    ns.add(5);
    ns.add(6);

    // Get a reverse view of the navigable set
    NavigableSet<Integer> reverseNs = ns.descendingSet();

    // Print the normal and reverse views
    System.out.println("Normal order: " + ns);
    System.out.println("Reverse order: " + reverseNs);

    NavigableSet<Integer> threeOrMore = ns.tailSet(3, true);
    System.out.println("3 or  more:  " + threeOrMore);
    System.out.println("lower(3): " + ns.lower(3));
    System.out.println("floor(3): " + ns.floor(3));
    System.out.println("higher(3): " + ns.higher(3));
    System.out.println("ceiling(3): " + ns.ceiling(3));

    System.out.println("pollFirst(): " + ns.pollFirst());
    System.out.println("Navigable Set:  " + ns);

    System.out.println("pollLast(): " + ns.pollLast());
    System.out.println("Navigable Set:  " + ns);

    System.out.println("pollFirst(): " + ns.pollFirst());
    System.out.println("Navigable Set:  " + ns);

    System.out.println("pollFirst(): " + ns.pollFirst());
    System.out.println("Navigable Set:  " + ns);

    System.out.println("pollFirst(): " + ns.pollFirst());
    System.out.println("Navigable Set:  " + ns);

    System.out.println("pollFirst(): " + ns.pollFirst());
    System.out.println("pollLast(): " + ns.pollLast());
}

From source file:com.eucalyptus.ws.util.HmacUtils.java

public static String makeV2SubjectString(String httpMethod, String host, String path,
        final Map<String, String> parameters) {
    parameters.remove("");
    StringBuilder sb = new StringBuilder();
    sb.append(httpMethod);/*from   ww w. ja v a  2  s  .c om*/
    sb.append("\n");
    sb.append(host);
    sb.append("\n");
    sb.append(path);
    sb.append("\n");
    String prefix = sb.toString();
    sb = new StringBuilder();
    NavigableSet<String> sortedKeys = new TreeSet<String>();
    sortedKeys.addAll(parameters.keySet());
    String firstKey = sortedKeys.pollFirst();
    if (firstKey != null) {
        sb.append(urlEncode(firstKey)).append("=")
                .append(urlEncode(parameters.get(firstKey).replaceAll("\\+", " ")));
    }
    while ((firstKey = sortedKeys.pollFirst()) != null) {
        sb.append("&").append(urlEncode(firstKey)).append("=")
                .append(urlEncode(parameters.get(firstKey).replaceAll("\\+", " ")));
    }
    String subject = prefix + sb.toString();
    LOG.trace("VERSION2: " + subject);
    return subject;
}

From source file:com.eucalyptus.auth.login.Hmacv2LoginModule.java

private String makeSubjectString(String httpMethod, String host, String path,
        final Map<String, String> parameters) throws UnsupportedEncodingException {
    URLCodec codec = new URLCodec();
    parameters.remove("");
    StringBuilder sb = new StringBuilder();
    sb.append(httpMethod);/*from   ww w . j  a  v a2 s  .c om*/
    sb.append("\n");
    sb.append(host);
    sb.append("\n");
    sb.append(path);
    sb.append("\n");
    String prefix = sb.toString();
    sb = new StringBuilder();
    NavigableSet<String> sortedKeys = new TreeSet<String>();
    sortedKeys.addAll(parameters.keySet());
    String firstKey = sortedKeys.pollFirst();
    if (firstKey != null) {
        sb.append(codec.encode(firstKey, "UTF-8")).append("=").append(
                codec.encode(Strings.nullToEmpty(parameters.get(firstKey)), "UTF-8").replaceAll("\\+", "%20"));
    }
    while ((firstKey = sortedKeys.pollFirst()) != null) {
        sb.append("&").append(codec.encode(firstKey, "UTF-8")).append("=").append(
                codec.encode(Strings.nullToEmpty(parameters.get(firstKey)), "UTF-8").replaceAll("\\+", "%20"));
    }
    String subject = prefix + sb.toString();
    LOG.trace("VERSION2: " + subject);
    return subject;
}

From source file:py.una.pol.karaku.menu.server.MenuServerLogic.java

private void handleRootMenu(Menu menu) {

    // Este hashSet se usa como un queue, solamente que es deseable que no
    // tenga valores repetidos
    NavigableSet<Menu> toSort = new TreeSet<Menu>();
    Map<Menu, Menu> parents = new HashMap<Menu, Menu>();
    toSort.add(menu);//from www. j  av  a  2s  . co  m
    Menu next;
    while (!toSort.isEmpty()) {

        next = toSort.pollFirst();
        handleMenu(next, parents.get(next));
        if (ListHelper.hasElements(next.getItems())) {
            sortInMemory(next.getItems());
            toSort.addAll(next.getItems());
            for (Menu m : next.getItems()) {
                parents.put(m, next);
            }
        }
    }
}

From source file:com.google.gwt.emultest.java.util.TreeSetTest.java

public void testPollFirst() {
    NavigableSet<E> set = createNavigableSet();

    assertNull(set.pollFirst());
    assertEquals(0, set.size());/*from  ww  w.  j  a  va  2 s . com*/

    set.add(getKeys()[0]);
    assertEquals(getKeys()[0], set.pollFirst());
    assertEquals(0, set.size());

    set.add(getKeys()[0]);
    set.add(getKeys()[1]);
    assertEquals(getKeys()[0], set.pollFirst());
    assertEquals(1, set.size());
    assertEquals(getKeys()[1], set.pollFirst());
    assertEquals(0, set.size());
    assertNull(set.pollFirst());
}

From source file:org.apache.hadoop.hbase.client.coprocessor.AggregationClient.java

/**
 * This is the client side interface/handler for calling the median method for a
 * given cf-cq combination. This method collects the necessary parameters
 * to compute the median and returns the median.
 * @param table/*w ww  . jav a2 s  . c o  m*/
 * @param ci
 * @param scan
 * @return R the median
 * @throws Throwable
 */
public <R, S, P extends Message, Q extends Message, T extends Message> R median(final HTable table,
        ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable {
    Pair<NavigableMap<byte[], List<S>>, List<S>> p = getMedianArgs(table, ci, scan);
    byte[] startRow = null;
    byte[] colFamily = scan.getFamilies()[0];
    NavigableSet<byte[]> quals = scan.getFamilyMap().get(colFamily);
    NavigableMap<byte[], List<S>> map = p.getFirst();
    S sumVal = p.getSecond().get(0);
    S sumWeights = p.getSecond().get(1);
    double halfSumVal = ci.divideForAvg(sumVal, 2L);
    double movingSumVal = 0;
    boolean weighted = false;
    if (quals.size() > 1) {
        weighted = true;
        halfSumVal = ci.divideForAvg(sumWeights, 2L);
    }

    for (Map.Entry<byte[], List<S>> entry : map.entrySet()) {
        S s = weighted ? entry.getValue().get(1) : entry.getValue().get(0);
        double newSumVal = movingSumVal + ci.divideForAvg(s, 1L);
        if (newSumVal > halfSumVal)
            break; // we found the region with the median
        movingSumVal = newSumVal;
        startRow = entry.getKey();
    }
    // scan the region with median and find it
    Scan scan2 = new Scan(scan);
    // inherit stop row from method parameter
    if (startRow != null)
        scan2.setStartRow(startRow);
    ResultScanner scanner = null;
    try {
        int cacheSize = scan2.getCaching();
        if (!scan2.getCacheBlocks() || scan2.getCaching() < 2) {
            scan2.setCacheBlocks(true);
            cacheSize = 5;
            scan2.setCaching(cacheSize);
        }
        scanner = table.getScanner(scan2);
        Result[] results = null;
        byte[] qualifier = quals.pollFirst();
        // qualifier for the weight column
        byte[] weightQualifier = weighted ? quals.pollLast() : qualifier;
        R value = null;
        do {
            results = scanner.next(cacheSize);
            if (results != null && results.length > 0) {
                for (int i = 0; i < results.length; i++) {
                    Result r = results[i];
                    // retrieve weight
                    Cell kv = r.getColumnLatest(colFamily, weightQualifier);
                    R newValue = ci.getValue(colFamily, weightQualifier, kv);
                    S s = ci.castToReturnType(newValue);
                    double newSumVal = movingSumVal + ci.divideForAvg(s, 1L);
                    // see if we have moved past the median
                    if (newSumVal > halfSumVal) {
                        return value;
                    }
                    movingSumVal = newSumVal;
                    kv = r.getColumnLatest(colFamily, qualifier);
                    value = ci.getValue(colFamily, qualifier, kv);
                }
            }
        } while (results != null && results.length > 0);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    return null;
}

From source file:org.apache.hadoop.hbase.client.transactional.TransactionalAggregationClient.java

/**
 * This is the client side interface/handler for calling the median method for a
 * given cf-cq combination. This method collects the necessary parameters
 * to compute the median and returns the median.
 * @param table// w w w.ja v  a 2  s  .  co  m
 * @param ci
 * @param scan
 * @return R the median
 * @throws Throwable
 */
public <R, S, P extends Message, Q extends Message, T extends Message> R median(final long transactionId,
        final TransactionalTable table, ColumnInterpreter<R, S, P, Q, T> ci, Scan scan) throws Throwable {
    Pair<NavigableMap<byte[], List<S>>, List<S>> p = getMedianArgs(transactionId, table, ci, scan);
    byte[] startRow = null;
    byte[] colFamily = scan.getFamilies()[0];
    NavigableSet<byte[]> quals = scan.getFamilyMap().get(colFamily);
    NavigableMap<byte[], List<S>> map = p.getFirst();
    S sumVal = p.getSecond().get(0);
    S sumWeights = p.getSecond().get(1);
    double halfSumVal = ci.divideForAvg(sumVal, 2L);
    double movingSumVal = 0;
    boolean weighted = false;
    if (quals.size() > 1) {
        weighted = true;
        halfSumVal = ci.divideForAvg(sumWeights, 2L);
    }

    for (Map.Entry<byte[], List<S>> entry : map.entrySet()) {
        S s = weighted ? entry.getValue().get(1) : entry.getValue().get(0);
        double newSumVal = movingSumVal + ci.divideForAvg(s, 1L);
        if (newSumVal > halfSumVal)
            break; // we found the region with the median
        movingSumVal = newSumVal;
        startRow = entry.getKey();
    }
    // scan the region with median and find it
    Scan scan2 = new Scan(scan);
    // inherit stop row from method parameter
    if (startRow != null)
        scan2.setStartRow(startRow);
    ResultScanner scanner = null;
    try {
        int cacheSize = scan2.getCaching();
        if (!scan2.getCacheBlocks() || scan2.getCaching() < 2) {
            scan2.setCacheBlocks(true);
            cacheSize = 5;
            scan2.setCaching(cacheSize);
        }
        scanner = table.getScanner(scan2);
        Result[] results = null;
        byte[] qualifier = quals.pollFirst();
        // qualifier for the weight column
        byte[] weightQualifier = weighted ? quals.pollLast() : qualifier;
        R value = null;
        do {
            results = scanner.next(cacheSize);
            if (results != null && results.length > 0) {
                for (int i = 0; i < results.length; i++) {
                    Result r = results[i];
                    // retrieve weight
                    Cell kv = r.getColumnLatest(colFamily, weightQualifier);
                    R newValue = ci.getValue(colFamily, weightQualifier, kv);
                    S s = ci.castToReturnType(newValue);
                    double newSumVal = movingSumVal + ci.divideForAvg(s, 1L);
                    // see if we have moved past the median
                    if (newSumVal > halfSumVal) {
                        return value;
                    }
                    movingSumVal = newSumVal;
                    kv = r.getColumnLatest(colFamily, qualifier);
                    value = ci.getValue(colFamily, qualifier, kv);
                }
            }
        } while (results != null && results.length > 0);
    } finally {
        if (scanner != null) {
            scanner.close();
        }
    }
    return null;
}

From source file:org.apache.hadoop.hbase.coprocessor.AggregateImplementation.java

/**
 * Gives the maximum for a given combination of column qualifier and column
 * family, in the given row range as defined in the Scan object. In its
 * current implementation, it takes one column family and one column qualifier
 * (if provided). In case of null column qualifier, maximum value for the
 * entire column family will be returned.
 *///  w ww.  j  a v  a  2  s.co m
@Override
public void getMax(RpcController controller, AggregateRequest request, RpcCallback<AggregateResponse> done) {
    InternalScanner scanner = null;
    AggregateResponse response = null;
    T max = null;
    try {
        ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
        T temp;
        Scan scan = ProtobufUtil.toScan(request.getScan());
        scanner = env.getRegion().getScanner(scan);
        List<Cell> results = new ArrayList<Cell>();
        byte[] colFamily = scan.getFamilies()[0];
        NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
        byte[] qualifier = null;
        if (qualifiers != null && !qualifiers.isEmpty()) {
            qualifier = qualifiers.pollFirst();
        }
        // qualifier can be null.
        boolean hasMoreRows = false;
        do {
            hasMoreRows = scanner.next(results);
            for (Cell kv : results) {
                temp = ci.getValue(colFamily, qualifier, kv);
                max = (max == null || (temp != null && ci.compare(temp, max) > 0)) ? temp : max;
            }
            results.clear();
        } while (hasMoreRows);
        if (max != null) {
            AggregateResponse.Builder builder = AggregateResponse.newBuilder();
            builder.addFirstPart(ci.getProtoForCellType(max).toByteString());
            response = builder.build();
        }
    } catch (IOException e) {
        ResponseConverter.setControllerException(controller, e);
    } finally {
        if (scanner != null) {
            try {
                scanner.close();
            } catch (IOException ignored) {
            }
        }
    }
    log.info("Maximum from this region is " + env.getRegion().getRegionNameAsString() + ": " + max);
    done.run(response);
}

From source file:org.apache.hadoop.hbase.coprocessor.AggregateImplementation.java

/**
 * Gives the minimum for a given combination of column qualifier and column
 * family, in the given row range as defined in the Scan object. In its
 * current implementation, it takes one column family and one column qualifier
 * (if provided). In case of null column qualifier, minimum value for the
 * entire column family will be returned.
 *///ww  w .j  a v a 2  s .  co  m
@Override
public void getMin(RpcController controller, AggregateRequest request, RpcCallback<AggregateResponse> done) {
    AggregateResponse response = null;
    InternalScanner scanner = null;
    T min = null;
    try {
        ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
        T temp;
        Scan scan = ProtobufUtil.toScan(request.getScan());
        scanner = env.getRegion().getScanner(scan);
        List<Cell> results = new ArrayList<Cell>();
        byte[] colFamily = scan.getFamilies()[0];
        NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
        byte[] qualifier = null;
        if (qualifiers != null && !qualifiers.isEmpty()) {
            qualifier = qualifiers.pollFirst();
        }
        boolean hasMoreRows = false;
        do {
            hasMoreRows = scanner.next(results);
            for (Cell kv : results) {
                temp = ci.getValue(colFamily, qualifier, kv);
                min = (min == null || (temp != null && ci.compare(temp, min) < 0)) ? temp : min;
            }
            results.clear();
        } while (hasMoreRows);
        if (min != null) {
            response = AggregateResponse.newBuilder().addFirstPart(ci.getProtoForCellType(min).toByteString())
                    .build();
        }
    } catch (IOException e) {
        ResponseConverter.setControllerException(controller, e);
    } finally {
        if (scanner != null) {
            try {
                scanner.close();
            } catch (IOException ignored) {
            }
        }
    }
    log.info("Minimum from this region is " + env.getRegion().getRegionNameAsString() + ": " + min);
    done.run(response);
}

From source file:org.apache.hadoop.hbase.coprocessor.AggregateImplementation.java

/**
 * Gives the sum for a given combination of column qualifier and column
 * family, in the given row range as defined in the Scan object. In its
 * current implementation, it takes one column family and one column qualifier
 * (if provided). In case of null column qualifier, sum for the entire column
 * family will be returned./*from ww w  .ja  v  a  2 s  .co m*/
 */
@Override
public void getSum(RpcController controller, AggregateRequest request, RpcCallback<AggregateResponse> done) {
    AggregateResponse response = null;
    InternalScanner scanner = null;
    long sum = 0l;
    try {
        ColumnInterpreter<T, S, P, Q, R> ci = constructColumnInterpreterFromRequest(request);
        S sumVal = null;
        T temp;
        Scan scan = ProtobufUtil.toScan(request.getScan());
        scanner = env.getRegion().getScanner(scan);
        byte[] colFamily = scan.getFamilies()[0];
        NavigableSet<byte[]> qualifiers = scan.getFamilyMap().get(colFamily);
        byte[] qualifier = null;
        if (qualifiers != null && !qualifiers.isEmpty()) {
            qualifier = qualifiers.pollFirst();
        }
        List<Cell> results = new ArrayList<Cell>();
        boolean hasMoreRows = false;
        do {
            hasMoreRows = scanner.next(results);
            for (Cell kv : results) {
                temp = ci.getValue(colFamily, qualifier, kv);
                if (temp != null)
                    sumVal = ci.add(sumVal, ci.castToReturnType(temp));
            }
            results.clear();
        } while (hasMoreRows);
        if (sumVal != null) {
            response = AggregateResponse.newBuilder()
                    .addFirstPart(ci.getProtoForPromotedType(sumVal).toByteString()).build();
        }
    } catch (IOException e) {
        ResponseConverter.setControllerException(controller, e);
    } finally {
        if (scanner != null) {
            try {
                scanner.close();
            } catch (IOException ignored) {
            }
        }
    }
    log.debug("Sum from this region is " + env.getRegion().getRegionNameAsString() + ": " + sum);
    done.run(response);
}