Example usage for java.util TreeMap isEmpty

List of usage examples for java.util TreeMap isEmpty

Introduction

In this page you can find the example usage for java.util TreeMap isEmpty.

Prototype

boolean isEmpty();

Source Link

Document

Returns true if this map contains no key-value mappings.

Usage

From source file:Main.java

public static void main(String[] a) {

    TreeMap map = new TreeMap();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    if (!map.isEmpty()) {
        Object last = map.lastKey();
        boolean first = true;
        do {//from   w w  w. j a  v  a 2 s .c  o m
            if (!first) {
                System.out.print(", ");
            }
            System.out.print(last);
            last = map.headMap(last).lastKey();
            first = false;
        } while (last != map.firstKey());
        System.out.println();
    }
}

From source file:Main.java

public static void main(String[] a) {
    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("key1", "value1");
    map.put("key2", "value2");
    map.put("key3", "value3");

    if (!map.isEmpty()) {
        String last = map.lastKey();
        boolean first = true;
        do {//from  w  w w .ja va2 s . co m
            if (!first) {
                System.out.print(", ");
            }
            System.out.print(last);
            last = map.headMap(last, true).lastKey();
            first = false;
        } while (last != map.firstKey());
        System.out.println();
    }
}

From source file:MainClass.java

public static void main(String args[]) {
    TreeMap map = new TreeMap();
    map.put("Virginia", "Richmond");
    map.put("Massachusetts", "Boston");
    map.put("New York", "Albany");
    map.put("Maryland", "Annapolis");

    if (!map.isEmpty()) {
        Object last = map.lastKey();
        boolean first = true;
        do {//from  w w  w  .  ja va  2 s. com
            if (!first) {
                System.out.print(", ");
            }
            System.out.print(last);
            last = map.headMap(last).lastKey();
            first = false;
        } while (last != map.firstKey());
        System.out.println();
    }
}

From source file:org.mycore.frontend.cli.MCRBasicCommands.java

/**
 * Shows the help text for one or more commands.
 *
 * @param pattern//from   ww w. ja v  a 2  s .  c o m
 *            the command, or a fragment of it
 */
@MCRCommand(syntax = "help {0}", help = "Show the help text for the commands beginning with {0}.", order = 10)
public static void listKnownCommandsBeginningWithPrefix(String pattern) {
    TreeMap<String, List<org.mycore.frontend.cli.MCRCommand>> matchingCommands = MCRCommandManager
            .getKnownCommands().entrySet().stream()
            .collect(Collectors.toMap(e -> e.getKey(),
                    e -> e.getValue().stream().filter(
                            cmd -> cmd.getSyntax().contains(pattern) || cmd.getHelpText().contains(pattern))
                            .collect(Collectors.toList()),
                    (k, v) -> k, TreeMap::new));

    matchingCommands.entrySet().removeIf(e -> e.getValue().isEmpty());

    if (matchingCommands.isEmpty()) {
        MCRCommandLineInterface.output("Unknown command:" + pattern);
    } else {
        MCRCommandLineInterface.output("");

        matchingCommands.forEach((grp, cmds) -> {
            outputGroup(grp);
            cmds.forEach(org.mycore.frontend.cli.MCRCommand::outputHelp);
        });
    }
}

From source file:ubic.gemma.model.association.coexpression.GeneCoexpressionNodeDegreeValueObject.java

private double[] asDoubleArray(TreeMap<Integer, Double> map) {
    DoubleArrayList list = new DoubleArrayList();
    if (map.isEmpty())
        return this.toPrimitive(list);
    list.setSize(Math.max(list.size(), map.lastKey() + 1));
    for (Integer s : map.keySet()) {
        list.set(s, map.get(s));/*  w  w  w.ja v a 2  s  . c  o  m*/
    }

    return this.toPrimitive(list);
}

From source file:ubic.gemma.model.association.coexpression.GeneCoexpressionNodeDegreeValueObject.java

private int[] asIntArray(TreeMap<Integer, Integer> nodedeg) {
    IntArrayList list = new IntArrayList();
    if (nodedeg.isEmpty())
        return this.toPrimitive(list);
    Integer maxSupport = nodedeg.lastKey();
    list.setSize(maxSupport + 1);//from  w  ww.  ja  v  a 2  s  . c o  m
    for (Integer s = 0; s <= maxSupport; s++) {
        if (nodedeg.containsKey(s)) {
            list.set(s, nodedeg.get(s));
        } else {
            list.set(s, 0);
        }
    }
    return this.toPrimitive(list);
}

From source file:com.datatorrent.contrib.hdht.HDHTBenchmarkTest.java

public void test() throws Exception {
    File file = new File(testInfo.getDir());
    FileUtils.deleteDirectory(file);/* w  ww. j a  va 2 s  .c o m*/

    LocalMode lma = LocalMode.newInstance();
    Configuration conf = new Configuration(false);
    conf.set("dt.operator.Store.fileStore.basePath", file.toURI().toString());
    //conf.set("dt.operator.Store.flushSize", "0");
    conf.set("dt.operator.Store.flushIntervalCount", "1");
    conf.set("dt.operator.Generator.attr.PARTITIONER",
            "com.datatorrent.lib.partitioner.StatelessPartitioner:2");

    lma.prepareDAG(new HDHTAppTest(), conf);
    LocalMode.Controller lc = lma.getController();
    lc.setHeartbeatMonitoringEnabled(false);
    lc.runAsync();

    long tms = System.currentTimeMillis();
    File f0 = new File(file, "0/0-0");
    File f1 = new File(file, "1/1-0");
    File wal0 = new File(file, "0/_WAL-0");
    File wal1 = new File(file, "1/_WAL-0");

    while (System.currentTimeMillis() - tms < 30000) {
        if (f0.exists() && f1.exists()) {
            break;
        }
        Thread.sleep(100);
    }
    lc.shutdown();

    Assert.assertTrue("exists " + f0, f0.exists() && f0.isFile());
    Assert.assertTrue("exists " + f1, f1.exists() && f1.isFile());
    Assert.assertTrue("exists " + wal0, wal0.exists() && wal0.exists());
    Assert.assertTrue("exists " + wal1, wal1.exists() && wal1.exists());

    FileAccessFSImpl fs = new MockFileAccess();
    fs.setBasePath(file.toURI().toString());
    fs.init();

    TreeMap<Slice, Slice> data = new TreeMap<>(new HDHTWriterTest.SequenceComparator());
    fs.getReader(0, "0-0").readFully(data);
    Assert.assertFalse(data.isEmpty());

    data.clear();
    fs.getReader(1, "1-0").readFully(data);
    Assert.assertFalse(data.isEmpty());

    fs.close();
}

From source file:com.linuxbox.enkive.imap.mongo.MongoImapAccountCreator.java

@Override
public void addImapMessages(String username, Date fromDate, Date toDate) throws MessageSearchException {

    Calendar startTime = Calendar.getInstance();
    startTime.setTime(fromDate);//from   w  ww.  j a  v a  2 s . c om
    Calendar endTime = Calendar.getInstance();
    endTime.setTime(toDate);

    while (startTime.before(endTime)) {
        Calendar endOfMonth = (Calendar) startTime.clone();
        endOfMonth.set(Calendar.DAY_OF_MONTH, endOfMonth.getActualMaximum(Calendar.DAY_OF_MONTH));

        if (endOfMonth.after(endTime))
            endOfMonth = (Calendar) endTime.clone();

        // Need to get all messages to add
        Set<String> messageIdsToAdd = getMailboxMessageIds(username, startTime.getTime(), endOfMonth.getTime());
        // Need to add messages
        // Get top UID, add from there
        if (!messageIdsToAdd.isEmpty()) {
            // Need to check if folder exists, if not create it and add to
            // user
            // mailbox list
            DBObject mailboxObject = getMessagesFolder(username, startTime.getTime());

            @SuppressWarnings("unchecked")
            HashMap<String, String> mailboxMsgIds = (HashMap<String, String>) mailboxObject
                    .get(MongoEnkiveImapConstants.MESSAGEIDS);

            TreeMap<String, String> sortedMsgIds = new TreeMap<String, String>();
            sortedMsgIds.putAll(mailboxMsgIds);
            long i = 0;
            if (!sortedMsgIds.isEmpty())
                i = Long.valueOf(sortedMsgIds.lastKey());

            for (String msgId : messageIdsToAdd) {
                i++;
                mailboxMsgIds.put(((Long.toString(i))), msgId);
            }
            mailboxObject.put(MongoEnkiveImapConstants.MESSAGEIDS, mailboxMsgIds);

            imapCollection.findAndModify(new BasicDBObject("_id", mailboxObject.get("_id")), mailboxObject);
        }
        startTime.set(Calendar.DAY_OF_MONTH, 1);
        startTime.add(Calendar.MONTH, 1);
    }
}

From source file:nl.rivm.cib.episim.model.disease.infection.MSEIRSTest.java

public static Observable<Entry<Double, long[]>> stochasticSellke(final SIRConfig config, final double maxDt) {
    return Observable.create(sub -> {
        final double beta = config.reproduction() / config.recovery();
        final long[] y = config.population();
        final double[] T = config.t();
        final double dt = Double.isFinite(maxDt) && maxDt > 0 ? maxDt : T[1];

        final Long seed = config.seed();
        final RandomGenerator rng = new MersenneTwister(seed == null ? System.currentTimeMillis() : seed);

        final ExponentialDistribution resistanceDist = new ExponentialDistribution(rng, 1),
                recoverDist = new ExponentialDistribution(rng, config.recovery());

        // pending infections (mapping resistance -> amount)
        final TreeMap<Double, Integer> tInfect = IntStream.range(0, (int) y[0])
                .mapToObj(i -> resistanceDist.sample())
                .collect(Collectors.toMap(r -> r, r -> 1, Integer::sum, TreeMap::new));
        // pending recoveries (mapping time -> amount)
        final TreeMap<Double, Integer> tRecover = new TreeMap<>();

        double cumPres = 0;
        // Re-initialize infectives as susceptibles with zero resistance
        tInfect.put(cumPres, (int) y[1]);
        y[0] += y[1]; // I -> S
        y[1] -= y[1]; // I -> 0
        for (double t = T[0]; t < T[1];) {
            publishCopy(sub, t, y);//  ww w . j av a2  s.  c o  m
            final long localPopSize = y[0] + y[1] + y[2];
            final Double ri = tInfect.isEmpty() ? null : tInfect.firstKey(), ti = ri == null ? null :
            // now + remaining resistance per relative pressure
            t + (ri - cumPres) / (beta * Math.max(y[1], 1) / localPopSize),
                    tr = tRecover.isEmpty() ? null : tRecover.firstKey();

            // time of next infection is earliest
            if (ti != null && (tr == null || ti < tr)) {
                final int ni = tInfect.remove(ri);
                cumPres = ri;

                // publish intermediate values
                for (double t1 = Math.min(ti, t + dt), tMax = Math.min(T[1], ti); t1 < tMax; t1 += dt)
                    publishCopy(sub, t1, y);

                // infect
                t = ti;
                y[0] -= ni; // from S
                y[1] += ni; // to I

                // schedule S_t recoveries at t+Exp(1/gamma)
                for (int i = 0; i < ni; i++)
                    tRecover.compute(t + recoverDist.sample(), (k, v) -> v == null ? 1 : v + 1);
            }
            // time of next recovery is earliest
            else if (tr != null) {
                final int nr = tRecover.remove(tr);
                if (ri != null)
                    // advance cumulative pressure by dt * relative pressure
                    cumPres += (tr - t) * beta * y[1] / localPopSize;

                // publish intermediate values
                for (double t1 = Math.min(tr, t + dt), tMax = Math.min(T[1], tr); t1 < tMax; t1 += dt)
                    publishCopy(sub, t1, y);

                // recover
                t = tr;
                y[1] -= nr; // from I
                y[2] += nr; // to R
            }
            // no events remaining
            else {
                // publish intermediate values
                for (double t1 = t + dt; t1 < T[1]; t1 += dt)
                    publishCopy(sub, t1, y);

                // time ends
                break;
            }
        }
        sub.onComplete();
    });
}

From source file:com.webcohesion.ofx4j.io.nanoxml.TestNanoXMLOFXReader.java

/**
 * tests whitespace before and after/*  ww  w .j av a2s  . com*/
 */
public void testWhitespaceBeforeAndAfter() throws Exception {
    NanoXMLOFXReader reader = new NanoXMLOFXReader();
    final Map<String, List<String>> headers = new HashMap<String, List<String>>();
    final Stack<Map<String, List<Object>>> aggregateStack = new Stack<Map<String, List<Object>>>();
    TreeMap<String, List<Object>> root = new TreeMap<String, List<Object>>();
    aggregateStack.push(root);

    reader.setContentHandler(getNewDefaultHandler(headers, aggregateStack));
    reader.parse(TestNanoXMLOFXReader.class.getResourceAsStream("whitespace-example.ofx"));
    assertEquals(9, headers.size());
    assertEquals(1, aggregateStack.size());
    assertSame(root, aggregateStack.pop());

    TreeMap<String, List<Object>> OFX = (TreeMap<String, List<Object>>) root.remove("OFX").get(0);
    assertNotNull(OFX);
    assertEquals("E", OFX.remove("S").get(0));
    assertTrue(OFX.isEmpty());
    assertTrue(root.isEmpty());
}