Example usage for java.util SortedMap headMap

List of usage examples for java.util SortedMap headMap

Introduction

In this page you can find the example usage for java.util SortedMap headMap.

Prototype

SortedMap<K, V> headMap(K toKey);

Source Link

Document

Returns a view of the portion of this map whose keys are strictly less than toKey .

Usage

From source file:Main.java

public static void main(String[] args) {
    SortedMap<String, Integer> sortedMap = new TreeMap<String, Integer>();
    sortedMap.put("A", 1);
    sortedMap.put("B", 2);
    sortedMap.put("C", 3);
    sortedMap.put("D", 4);
    sortedMap.put("E", 5);
    sortedMap.put("java2s", 6);

    SortedMap<String, Integer> map = sortedMap.headMap("C");
    System.out.println(map);/*from w w  w. j ava 2  s.  com*/

}

From source file:FocusTraversalExample.java

public Component getComponentBefore(Container focusCycleRoot, Component aComponent) {
    if (!(aComponent instanceof JButton)) {
        return null;
    }/*from   ww  w  .j  ava  2  s . c  o  m*/

    SortedMap buttons = getSortedButtons(focusCycleRoot);
    SortedMap prevButtons = // Find all buttons before this one.
            buttons.headMap(((JButton) aComponent).getText());
    if (prevButtons.isEmpty()) { // Wrapped back to end.
        if (!buttons.isEmpty()) {
            return (Component) buttons.get(buttons.lastKey());
        }
        return null; // Degenerate case of no buttons.
    }
    return (Component) prevButtons.get(prevButtons.lastKey());
}

From source file:hudson.Functions.java

/**
 * Creates a sub map by using the given range (both ends inclusive).
 *///from   w  w  w  .java2  s .  c  o  m
public static <V> SortedMap<Integer, V> filter(SortedMap<Integer, V> map, String from, String to) {
    if (from == null && to == null)
        return map;
    if (to == null)
        return map.headMap(Integer.parseInt(from) - 1);
    if (from == null)
        return map.tailMap(Integer.parseInt(to));

    return map.subMap(Integer.parseInt(to), Integer.parseInt(from) - 1);
}

From source file:com.romeikat.datamessie.core.base.util.CollectionUtil.java

public SortedMap<String, Double> getFirstItems(final SortedMap<String, Double> map, final int numberOfItems) {
    if (numberOfItems <= 0) {
        return Collections.emptySortedMap();
    }//from www. jav a 2s  .co  m

    // Limit to first N terms
    String lastTerm = null;
    int i = 0;
    for (final String term : map.keySet()) {
        if (i == numberOfItems) {
            break;
        }

        lastTerm = term;
        i++;
    }

    return map.headMap(lastTerm);
}

From source file:com.palantir.atlasdb.transaction.impl.SnapshotTransaction.java

/**
 * This includes deleted writes as zero length byte arrays, be sure to strip them out.
 *//* w ww  .  jav a  2s.c  o  m*/
private SortedMap<Cell, byte[]> getLocalWritesForRange(String tableName, byte[] startRow, byte[] endRow) {
    SortedMap<Cell, byte[]> writes = getLocalWrites(tableName);
    if (startRow.length != 0) {
        writes = writes.tailMap(Cells.createSmallestCellForRow(startRow));
    }
    if (endRow.length != 0) {
        writes = writes.headMap(Cells.createSmallestCellForRow(endRow));
    }
    return writes;
}

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

/**
 * Test method for 'java.util.SortedMap.headMap(Object, Object)'.
 *
 * @see java.util.SortedMap#headMap(Object)
 *//*from  w w  w . j  av  a 2 s.  com*/
public void testHeadMap_throwsNullPointerException() {
    SortedMap<K, V> sortedMap = createNavigableMap();
    try {
        sortedMap.headMap(null);
        assertTrue(useNullKey());
    } catch (NullPointerException e) {
        assertFalse(useNullKey());
    }
}

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

/**
 * Test method for 'java.util.SortedMap.headMap(Object, Object)'.
 *
 * @see java.util.SortedMap#headMap(Object)
 */// w  w w.j  a v a2  s .  c  o  m
@SuppressWarnings("unchecked")
public void testHeadMap_throwsClassCastException() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    SortedMap sortedMap = createNavigableMap();
    if (isNaturalOrder()) {
        // TODO Why does this succeed with natural ordering when subMap doesn't?
        sortedMap.headMap(getConflictingKey());
    } else {
        try {
            sortedMap.headMap(getConflictingKey());
            fail("ClassCastException expected");
        } catch (ClassCastException expected) {
        }
    }

    sortedMap.put(keys[0], values[0]);
    if (isNaturalOrder()) {
        // TODO Why does this succeed with natural ordering when subMap doesn't?
        sortedMap.headMap(getConflictingKey());
    } else {
        try {
            sortedMap.headMap(getConflictingKey());
            fail("ClassCastException expected");
        } catch (ClassCastException expected) {
        }
    }
}

From source file:edu.vt.middleware.ldap.search.SearchExecutor.java

/**
 * This performs a Ldap search with the supplied <code>Query</code>.
 *
 * @param  ldapPool  <code>LdapPool</code> to use for searching
 * @param  query  <code>Query</code> to search for
 *
 * @return  <code>Iterator</code> - of search results
 *
 * @throws  PeopleSearchException  if an error occurs searching the Ldap
 *///from  ww w.  j  av a  2  s  .com
public Iterator<SearchResult> executeSearch(final LdapPool<Ldap> ldapPool, final Query query)
        throws PeopleSearchException {
    final SortedMap<Integer, SearchResult> m = new TreeMap<Integer, SearchResult>();
    final List<String> l = new ArrayList<String>();

    if (this.queryTemplates != null && this.queryTemplates.size() > 0) {
        final SearchThread[] threads = new SearchThread[this.queryTemplates.size()];
        for (int i = 1; i <= this.queryTemplates.size(); i++) {
            final String ldapQuery = this.buildLdapQuery(this.getQueryTemplate(query.getQueryParameters(), i),
                    query.getSearchRestrictions());
            if (ldapQuery != null) {
                threads[i - 1] = new SearchThread(ldapPool, ldapQuery, query.getQueryAttributes());
            } else {
                threads[i - 1] = null;
            }
        }
        if (LOG.isDebugEnabled()) {
            LOG.debug("Performing search with " + threads.length + " threads");
        }

        int count = 0;
        boolean loop = true;
        while (loop && count < threads.length) {
            List<QueryResult> results = null;
            if (additive) {
                results = this.doAdditiveSearch(threads);
            } else {
                results = this.doIterativeSearch(threads[count]);
            }

            if (LOG.isDebugEnabled()) {
                LOG.debug("Loop " + count + " found " + results.size() + " results");
            }
            for (int i = 0; i < results.size(); i++) {
                int j = m.size();
                final QueryResult qr = results.get(i);
                if (qr != null) {
                    final SearchResult sr = qr.getSearchResult();
                    if (sr != null) {
                        if (!l.contains(sr.getName())) {
                            if (additive) {
                                qr.setSearchIteration(i);
                                qr.setTermCount(this.termCount);
                                this.processResults(qr);
                            } else {
                                qr.setSearchIteration(count);
                                qr.setTermCount(this.termCount);
                                this.processResults(qr);
                            }
                            // store for results
                            m.put(new Integer(j++), sr);
                            l.add(sr.getName());
                            if (LOG.isDebugEnabled()) {
                                if (LOG.isDebugEnabled()) {
                                    LOG.debug("Query " + (additive ? i : count) + " found: " + sr.getName());
                                }
                            }
                        }
                    }
                }
            }
            if (additive || !m.isEmpty()) {
                loop = false;
            } else {
                count++;
            }
        }
    } else {
        if (LOG.isWarnEnabled()) {
            LOG.warn("No searches configured");
        }
    }

    Iterator<SearchResult> i = null;
    if (query.getFromResult() != null) {
        if (query.getToResult() != null) {
            if (query.getFromResult().intValue() <= query.getToResult().intValue()) {
                i = m.subMap(query.getFromResult(), query.getToResult()).values().iterator();
            }
        } else {
            i = m.tailMap(query.getFromResult()).values().iterator();
        }
    } else if (query.getToResult() != null) {
        i = m.headMap(query.getToResult()).values().iterator();
    } else {
        i = m.values().iterator();
    }
    return i;
}

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

/**
 * Test method for 'java.util.SortedMap.lastKey()'.
 *
 * @see java.util.SortedMap#lastKey()/*from   www. java2 s .  co m*/
 */
public void testLastKey() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    SortedMap<K, V> map = createNavigableMap();

    // test with a single entry map
    map.put(keys[0], values[0]);
    assertEquals(keys[0], map.lastKey());
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[0], map.lastKey());
    assertEquals(keys[0], map.firstKey());
    assertEquals(map.firstKey(), map.lastKey());

    // test with two entry map
    map.put(keys[1], values[1]);
    assertEquals(keys[1], map.lastKey());
    assertFalse(keys[0].equals(map.lastKey()));
    // is it consistent with other methods
    assertEquals(map.keySet().toArray()[1], map.lastKey());
    assertEquals(keys[0], map.firstKey());
    assertFalse(map.firstKey().equals(map.lastKey()));

    map.put(keys[2], values[2]);
    map.put(keys[3], values[3]);
    assertEquals(keys[0], map.headMap(keys[1]).lastKey());
    assertEquals(keys[keys.length - 1], map.tailMap(keys[2]).lastKey());
    assertEquals(keys[2], map.subMap(keys[1], keys[3]).lastKey());
}

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

/**
 * Test method for 'java.util.Map.put(Object, Object)'. This test shows some
 * bad behavior of the TreeMap class before JDK 7. A mapping with null key can
 * be put in but several methods are are unusable afterward.
 *
 * A SortedMap with natural ordering (no comparator) is supposed to throw a
 * null pointer exception if a null keys are "not supported". For a natural
 * ordered TreeMap before JDK 7, a null pointer exception is not thrown. But,
 * the map is left in a state where any other key based methods result in a
 * null pointer exception./*w ww  .j ava 2  s .  c  o m*/
 *
 * @see java.util.Map#put(Object, Object)
 */
public void testPut_nullKey() {
    K[] keys = getSortedKeys();
    V[] values = getSortedValues();
    SortedMap<K, V> sortedMap = createNavigableMap();

    if (useNullKey()) {
        assertNull(sortedMap.put(null, values[0]));
        assertTrue(sortedMap.containsValue(values[0]));

        // the map methods the continue to function
        sortedMap.containsValue(null);
        sortedMap.containsValue(values[0]);
        sortedMap.entrySet();
        sortedMap.equals(createMap());
        sortedMap.hashCode();
        sortedMap.isEmpty();
        sortedMap.keySet();
        sortedMap.putAll(createMap());
        sortedMap.size();
        sortedMap.values();

        // all of the sorted map methods still function
        sortedMap.comparator();
        sortedMap.firstKey();
        sortedMap.lastKey();
        sortedMap.subMap(getLessThanMinimumKey(), getGreaterThanMaximumKey());
        sortedMap.headMap(getLessThanMinimumKey());
        sortedMap.tailMap(getLessThanMinimumKey());
    } else if (TestUtils.getJdkVersion() > 6) {
        // nulls are rejected immediately and don't poison the map anymore
        try {
            assertNull(sortedMap.put(null, values[0]));
            fail("should have thrown");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            assertNull(sortedMap.put(null, values[1]));
            fail("expected exception adding second null");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(null);
            fail("expected exception on containsKey(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        sortedMap.containsKey(keys[0]);
        try {
            sortedMap.get(null);
            fail("expected exception on get(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        sortedMap.get(keys[0]);
        try {
            sortedMap.remove(null);
        } catch (NullPointerException e) {
            // expected
        }
        sortedMap.remove(keys[0]);
    } else {
        // before JDK 7, nulls poisoned the map
        try {
            assertNull(sortedMap.put(null, values[0]));
            // note: first null added is not required to throw NPE since no
            // comparisons are needed
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            assertNull(sortedMap.put(null, values[1]));
            fail("expected exception adding second null");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(null);
            fail("expected exception on containsKey(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.containsKey(keys[0]);
            fail("expected exception on contains(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.get(null);
            fail("expected exception on get(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.get(keys[0]);
            fail("expected exception on get(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.remove(null);
            fail("expected exception on remove(null)");
        } catch (NullPointerException e) {
            // expected outcome
        }
        try {
            sortedMap.remove(keys[0]);
            fail("expected exception on remove(key)");
        } catch (NullPointerException e) {
            // expected outcome
        }
    }
}