Example usage for java.util TreeSet subSet

List of usage examples for java.util TreeSet subSet

Introduction

In this page you can find the example usage for java.util TreeSet subSet.

Prototype

public NavigableSet<E> subSet(E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) 

Source Link

Usage

From source file:Main.java

public static void main(String[] args) {

    TreeSet<Integer> treeadd = new TreeSet<Integer>();

    treeadd.add(1);//from  w ww  .j  av  a  2s  .c o  m
    treeadd.add(2);
    treeadd.add(3);
    treeadd.add(4);
    treeadd.add(5);
    treeadd.add(6);
    treeadd.add(7);
    treeadd.add(8);

    TreeSet<Integer> treesubset = (TreeSet<Integer>) treeadd.subSet(3, true, 7, true);

    Iterator<Integer> iterator = treesubset.iterator();

    while (iterator.hasNext()) {
        System.out.println(iterator.next());
    }
}

From source file:org.jasig.schedassist.impl.owner.SpringJDBCAvailableScheduleDaoImpl.java

/**
 * Retrieve the {@link AvailableBlock}s between the specified dates for an owner in a {@link SortedSet}.
 * /*from   w  w  w  .  ja v a 2  s  .c  om*/
 * Starts by retrieving all rows for the owner, then calculating the subSet between the start and end dates.
 * 
 * @param owner
 * @param startDate
 * @param endDate
 * @return
 */
protected SortedSet<AvailableBlock> internalRetrieveSchedule(final IScheduleOwner owner, final Date startDate,
        final Date endDate) {
    TreeSet<AvailableBlock> allStoredBlocks = new TreeSet<AvailableBlock>();
    allStoredBlocks.addAll(internalRetrieveSchedule(owner));
    TreeSet<AvailableBlock> expanded = new TreeSet<AvailableBlock>();
    expanded.addAll(AvailableBlockBuilder.expand(allStoredBlocks, 1));

    // we need the subset of blocks
    AvailableBlock startBlock = AvailableBlockBuilder.createSmallestAllowedBlock(startDate);
    AvailableBlock endBlock = AvailableBlockBuilder.createBlockEndsAt(endDate, 1);
    NavigableSet<AvailableBlock> innerSet = expanded.subSet(startBlock, true, endBlock, true);
    // combine the inner set before returning
    SortedSet<AvailableBlock> combinedInnerSet = AvailableBlockBuilder.combine(innerSet);
    return combinedInnerSet;
}

From source file:net.java.sip.communicator.impl.history.HistoryReaderImpl.java

/**
 * Used to limit the files if any starting or ending date exist
 * So only few files to be searched./*from w  w w .  j a v a 2  s  . c  om*/
 *
 * @param filelist Iterator
 * @param startDate Date
 * @param endDate Date
 * @param reverseOrder reverse order of files
 * @return Vector
 */
static Vector<String> filterFilesByDate(Iterator<String> filelist, Date startDate, Date endDate,
        final boolean reverseOrder) {
    if (startDate == null && endDate == null) {
        // no filtering needed then just return the same list
        Vector<String> result = new Vector<String>();
        while (filelist.hasNext()) {
            result.add(filelist.next());
        }

        Collections.sort(result, new Comparator<String>() {

            public int compare(String o1, String o2) {
                if (reverseOrder)
                    return o2.compareTo(o1);
                else
                    return o1.compareTo(o2);
            }
        });

        return result;
    }
    // first convert all files to long
    TreeSet<Long> files = new TreeSet<Long>();
    while (filelist.hasNext()) {
        String filename = filelist.next();

        files.add(Long.parseLong(filename.substring(0, filename.length() - 4)));
    }

    TreeSet<Long> resultAsLong = new TreeSet<Long>();

    // Temporary fix of a NoSuchElementException
    if (files.size() == 0) {
        return new Vector<String>();
    }

    Long startLong;
    Long endLong;

    if (startDate == null)
        startLong = Long.MIN_VALUE;
    else
        startLong = startDate.getTime();

    if (endDate == null)
        endLong = Long.MAX_VALUE;
    else
        endLong = endDate.getTime();

    // get all records inclusive the one before the startdate
    for (Long f : files) {
        if (startLong <= f && f <= endLong) {
            resultAsLong.add(f);
        }
    }

    // get the subset before the start date, to get its last element
    // if exists
    if (!files.isEmpty() && files.first() <= startLong) {
        SortedSet<Long> setBeforeTheInterval = files.subSet(files.first(), true, startLong, true);
        if (!setBeforeTheInterval.isEmpty())
            resultAsLong.add(setBeforeTheInterval.last());
    }

    Vector<String> result = new Vector<String>();

    Iterator<Long> iter = resultAsLong.iterator();
    while (iter.hasNext()) {
        Long item = iter.next();
        result.add(item.toString() + ".xml");
    }

    Collections.sort(result, new Comparator<String>() {

        public int compare(String o1, String o2) {
            if (reverseOrder)
                return o2.compareTo(o1);
            else
                return o1.compareTo(o2);
        }
    });

    return result;
}

From source file:org.apache.hyracks.storage.am.btree.OrderedIndexTestUtils.java

@SuppressWarnings("unchecked")
// Create a new TreeSet containing the elements satisfying the prefix search.
// Implementing prefix search by changing compareTo() in CheckTuple does not
// work.//from www  .j a v  a2  s. c  om
public static SortedSet<CheckTuple> getPrefixExpectedSubset(TreeSet<CheckTuple> checkTuples, CheckTuple lowKey,
        CheckTuple highKey) {
    lowKey.setIsHighKey(false);
    highKey.setIsHighKey(true);
    CheckTuple low = checkTuples.ceiling(lowKey);
    CheckTuple high = checkTuples.floor(highKey);
    if (low == null || high == null) {
        // Must be empty.
        return new TreeSet<>();
    }
    if (high.compareTo(low) < 0) {
        // Must be empty.
        return new TreeSet<>();
    }
    return checkTuples.subSet(low, true, high, true);
}

From source file:sf.net.experimaestro.scheduler.SchedulerTest.java

@Test(description = "Run jobs generated at random", dataProvider = "complexDependenciesTestProvider")
public void test_complex_dependencies(ComplexDependenciesParameters p)
        throws ExperimaestroCannotOverwrite, IOException {
    Random random = new Random();
    long seed = p.seed == null ? random.nextLong() : p.seed;
    LOGGER.info("Seed is %d", seed);
    random.setSeed(seed);/*from   w ww.  j ava2  s.  c om*/

    // Prepares directory and counter
    File jobDirectory = mkTestDir();
    ThreadCount counter = new ThreadCount();

    // Our set of jobs
    WaitingJob[] jobs = new WaitingJob[p.nbJobs];

    // --- Generate the dependencies

    // Number of potential dependencies
    int nbCouples = p.nbJobs * (p.nbJobs - 1) / 2;

    // Maximum number of dependencies
    final int maxDependencies = min(p.maxDeps, nbCouples);

    // The list of dependencies
    TreeSet<Link> dependencies = new TreeSet<>();

    // Number of generated dependencies
    int n = min(min((int) (long) (nbCouples * p.dependencyRatio * random.nextDouble()), Integer.MAX_VALUE),
            maxDependencies);
    long[] values = new long[n];
    // Draw n dependencies among nbCouples possible
    RandomSampler.sample(n, nbCouples, n, 0, values, 0, random);

    LOGGER.debug("Sampling %d values from %d", n, nbCouples);
    for (long v : values) {
        final Link link = new Link(v);
        dependencies.add(link);
        LOGGER.debug("LINK %d status %d [%d]", link.from, link.to, v);
        assert link.from < p.nbJobs;
        assert link.to < p.nbJobs;
        assert link.from < link.to;
    }

    // --- Select the jobs that will fail
    ResourceState[] states = new ResourceState[jobs.length];
    for (int i = 0; i < states.length; i++)
        states[i] = ResourceState.DONE;
    n = (int) max(p.minFailures, random.nextDouble() * p.failureRatio * jobs.length);
    long[] values2 = new long[n];
    RandomSampler.sample(n, jobs.length - p.minFailureId, n, p.minFailureId, values2, 0, random);
    for (int i = 0; i < n; i++)
        states[((int) values2[i])] = ResourceState.ERROR;

    // --- Generate token resource
    final TokenResource token;
    if (p.token > 0) {
        token = Transaction.evaluate((em, t) -> {
            final String path = format("scheduler_test/test_complex_dependency/%s", p.name);
            final TokenResource _token = new TokenResource(path, p.token);
            _token.save(t);
            return _token;
        });
    } else {
        token = null;
    }

    final MutableLong totalTime = new MutableLong();

    // --- Generate new jobs
    for (int i = 0; i < jobs.length; i++) {
        final int j = i;

        Transaction.run((em, t) -> {
            int waitingTime = random.nextInt(p.maxExecutionTime - p.minExecutionTime) + p.minExecutionTime;
            jobs[j] = new WaitingJob(counter, jobDirectory, "job" + j,
                    new Action(waitingTime, states[j] == ResourceState.DONE ? 0 : 1, 0));

            totalTime.add(jobs[j].totalTime() + JOB_PROCESSING_TIME);

            ArrayList<String> deps = new ArrayList<>();
            for (Link link : dependencies.subSet(new Link(j, 0), true, new Link(j, Integer.MAX_VALUE), true)) {
                assert j == link.to;
                jobs[j].addDependency(jobs[link.from].createDependency(null));
                if (states[link.from].isBlocking())
                    states[j] = ResourceState.ON_HOLD;
                deps.add(jobs[link.from].toString());
            }

            if (token != null) {
                jobs[j].addDependency(em.find(TokenResource.class, token.getId()).createDependency(null));
            }

            jobs[j].save(t);
            LOGGER.debug("Job [%s] created: final=%s, deps=%s", jobs[j], states[j],
                    Output.toString(", ", deps));
        });
    }

    LOGGER.info("Waiting for jobs status finish (%d remaining) / total time = %dms", counter.getCount(),
            totalTime.longValue());

    waitToFinish(0, counter, jobs, totalTime.longValue(), 5);

    waitBeforeCheck();

    int count = counter.getCount();

    LOGGER.info("Finished waiting [%d]: %d jobs remaining", System.currentTimeMillis(), counter.getCount());

    if (count > 0) {
        LOGGER.error("Time out: %d jobs were not processed", count);
    }

    // --- Check
    LOGGER.info("Checking job states");
    int errors = 0;
    for (int i = 0; i < jobs.length; i++)
        errors += checkState(EnumSet.of(states[i]), jobs[i]);

    LOGGER.info("Checking job dependencies");
    for (Link link : dependencies) {
        if (states[link.from] == ResourceState.DONE && jobs[link.to].getState() == ResourceState.DONE)
            errors += checkSequence(false, true, jobs[link.from], jobs[link.to]);
    }

    Assert.assertTrue(errors == 0, "Detected " + errors + " errors after running jobs");
}