Example usage for java.util SortedSet headSet

List of usage examples for java.util SortedSet headSet

Introduction

In this page you can find the example usage for java.util SortedSet headSet.

Prototype

SortedSet<E> headSet(E toElement);

Source Link

Document

Returns a view of the portion of this set whose elements are strictly less than toElement .

Usage

From source file:Tail.java

public static void main(String args[]) throws Exception {
    String elements[] = { "Irish Setter", "Poodle", "English Setter", "Gordon Setter", "Pug" };
    SortedSet set = new TreeSet(Arrays.asList(elements));
    System.out.println(set.tailSet("Irish Setter"));
    System.out.println(set.headSet("Irish Setter"));
    System.out.println(set.headSet("Irish Setter\0"));
    System.out.println(set.tailSet("Irish Setter\0"));
    System.out.println(set.subSet("Irish Setter", "Poodle\0"));
    System.out.println(set.subSet("Irish Setter", "Irish Setter\0"));
    System.out.println(set.subSet("Irish Setter", "Irish Setter"));
}

From source file:MainClass.java

public static void main(String args[]) throws Exception {
    String elements[] = { "I", "P", "E", "G", "P" };
    SortedSet set = new TreeSet(Arrays.asList(elements));
    System.out.println(set.tailSet("I"));
    System.out.println(set.headSet("I"));
    System.out.println(set.headSet("I\0"));
    System.out.println(set.tailSet("I\0"));
    System.out.println(set.subSet("I", "P\0"));
    System.out.println(set.subSet("I", "I\0"));
    System.out.println(set.subSet("I", "I"));
}

From source file:Main.java

public static void main(String[] args) {
    SortedSet<String> names = new TreeSet<>();
    names.add("HTML");
    names.add("Java");
    names.add("SQL");
    names.add("CSS");
    System.out.println("Sorted Set: " + names);
    System.out.println("First: " + names.first());
    System.out.println("Last: " + names.last());

    SortedSet<String> ssBeforeCSS = names.headSet("CSS");
    System.out.println(ssBeforeCSS);

    SortedSet<String> ssBetwenCSSAndHTML = names.subSet("CSS", "HTML");
    System.out.println(ssBetwenCSSAndHTML);

    SortedSet<String> ssBetwenCSSAndHTML2 = names.subSet("CSS", "HTML");
    System.out.println(ssBetwenCSSAndHTML2);

    SortedSet<String> ssCSSAndAfter = names.tailSet("CSS");
    System.out.println(ssCSSAndAfter);

}

From source file:Main.java

public static void main(String args[]) {
    Employee emps[] = { new Employee("Finance", "Degree, Debbie"), new Employee("Finance", "Grade, Geri"),
            new Employee("Finance", "Extent, Ester"), new Employee("Engineering", "Measure, Mary"),
            new Employee("Engineering", "Amount, Anastasia"), new Employee("Engineering", "Ratio, Ringo"),
            new Employee("Sales", "Stint, Sarah"), new Employee("Sales", "Pitch, Paula"),
            new Employee("Support", "Rate, Rhoda"), };
    SortedSet set = new TreeSet(Arrays.asList(emps));
    System.out.println(set);/*from   w w  w  .ja  v  a2s . c  om*/

    try {
        Object last = set.last();
        boolean first = true;
        while (true) {
            if (!first) {
                System.out.print(", ");
            }
            System.out.println(last);
            last = set.headSet(last).last();
        }
    } catch (NoSuchElementException e) {
        System.out.println();
    }

    Set subset = set.headSet(emps[4]);
    subset.add(emps[5]);

}

From source file:SortedSetDemo.java

public static void main(String[] args) {
    SortedSet sortedSet = new TreeSet(Arrays.asList("one two three four five six seven eight".split(" ")));
    System.out.println(sortedSet);
    Object low = sortedSet.first(), high = sortedSet.last();
    System.out.println(low);//from ww w .  j av a  2  s  .c  o m
    System.out.println(high);
    Iterator it = sortedSet.iterator();
    for (int i = 0; i <= 6; i++) {
        if (i == 3)
            low = it.next();
        if (i == 6)
            high = it.next();
        else
            it.next();
    }
    System.out.println(low);
    System.out.println(high);
    System.out.println(sortedSet.subSet(low, high));
    System.out.println(sortedSet.headSet(high));
    System.out.println(sortedSet.tailSet(low));
}

From source file:com.ngdata.hbaseindexer.util.zookeeper.ZkLock.java

/**
 * Try to get a lock, waits until this succeeds.
 *
 * @param lockPath path in ZooKeeper below which the ephemeral lock nodes will be created. This path should
 *                 exist prior to calling this method.
 *
 * @return a string identifying this lock, needs to be supplied to {@link ZkLock#unlock}.
 *///  w w  w.java  2  s.  c  o m
public static String lock(final ZooKeeperItf zk, final String lockPath) throws ZkLockException {
    if (zk.isCurrentThreadEventThread()) {
        throw new RuntimeException("ZkLock should not be used from within the ZooKeeper event thread.");
    }

    try {
        final long threadId = Thread.currentThread().getId();

        // Quote from ZK lock recipe:
        //    1. Call create( ) with a pathname of "_locknode_/lock-" and the sequence and ephemeral flags set.
        zk.retryOperation(new ZooKeeperOperation<String>() {
            @Override
            public String execute() throws KeeperException, InterruptedException {
                return zk.create(lockPath + "/lock-" + threadId + "-", null, ZooDefs.Ids.OPEN_ACL_UNSAFE,
                        CreateMode.EPHEMERAL_SEQUENTIAL);
            }
        });

        while (true) {
            // Quote from ZK lock recipe:
            //    2. Call getChildren( ) on the lock node without setting the watch flag (this is important to avoid
            //       the herd effect).
            List<ZkLockNode> children = parseChildren(zk.retryOperation(new ZooKeeperOperation<List<String>>() {
                @Override
                public List<String> execute() throws KeeperException, InterruptedException {
                    return zk.getChildren(lockPath, null);
                }
            }));

            ZkLockNode myLockNode = null;
            String myLockName = null;
            String myLockPath = null;
            for (ZkLockNode child : children) {
                // if the child has the same thread id and session id as us, then it is our lock
                if (child.getThreadId() == threadId) {
                    final String childPath = lockPath + "/" + child.getName();
                    Stat stat = zk.retryOperation(new ZooKeeperOperation<Stat>() {
                        @Override
                        public Stat execute() throws KeeperException, InterruptedException {
                            return zk.exists(childPath, false);
                        }
                    });
                    if (stat != null && stat.getEphemeralOwner() == zk.getSessionId()) {
                        if (myLockName != null) {
                            // We have found another lock node which belongs to us.
                            // This means that the lock creation above was executed twice, which can occur
                            // in case of connection loss. Delete this node to avoid that otherwise it would
                            // never be released.
                            zk.retryOperation(new ZooKeeperOperation<Object>() {
                                @Override
                                public Object execute() throws KeeperException, InterruptedException {
                                    try {
                                        zk.delete(childPath, -1);
                                    } catch (KeeperException.NoNodeException e) {
                                        // ignore
                                    }
                                    return null;
                                }
                            });
                        } else {
                            myLockNode = child;
                            myLockName = child.getName();
                            myLockPath = childPath;
                        }
                    }
                }
            }

            if (myLockName == null) {
                throw new ZkLockException("Unexpected problem: did not find our lock node.");
            }

            // Idea to use SortedSets seen in a ZK recipe
            SortedSet<ZkLockNode> sortedChildren = new TreeSet<ZkLockNode>(children);
            SortedSet<ZkLockNode> lowerThanMe = sortedChildren.headSet(myLockNode);

            // Quote from ZK lock recipe:
            //    3. If the pathname created in step 1 has the lowest sequence number suffix, the client has the lock
            //       and the client exits the protocol.
            if (lowerThanMe.isEmpty()) {
                // We have the lock
                return myLockPath;
            }

            // Quote from ZK lock recipe:
            //    4. The client calls exists( ) with the watch flag set on the path in the lock directory with the
            //       next lowest sequence number.

            final String pathToWatch = lockPath + "/" + lowerThanMe.last().name;
            final Object condition = new Object();
            final MyWatcher watcher = new MyWatcher(pathToWatch, condition);

            Stat stat = zk.retryOperation(new ZooKeeperOperation<Stat>() {
                @Override
                public Stat execute() throws KeeperException, InterruptedException {
                    return zk.exists(pathToWatch, watcher);
                }
            });

            if (stat == null) {
                // Quote from ZK lock recipe:
                //    5a. if exists( ) returns false, go to step 2.

                // This means (I think) that the lock was removed (explicitly or through session expiration) between
                // the moment we queried for the children and the moment we called exists()

                // If the node does not exist, the watcher will still be left, does not seem so tidy, hopefully
                // this situation does not occur often.

                // Let's log it to keep an eye on it
                LogFactory.getLog(ZkLock.class).warn("Next lower lock node does not exist: " + pathToWatch);
            } else {
                // Quote from ZK lock recipe:
                //    5b. Otherwise, wait for a notification for the pathname from the previous step before going
                //        to step 2.
                synchronized (condition) {
                    while (!watcher.gotNotified) {
                        condition.wait();
                    }
                }
            }
        }
    } catch (Throwable t) {
        throw new ZkLockException("Error obtaining lock, path: " + lockPath, t);
    }
}

From source file:com.opengamma.integration.coppclark.CoppClarkHolidayFileReader.java

private void mergeDates(HolidayDocument existingDoc, HolidayDocument newDoc) {
    if (newDoc.getHoliday().getHolidayDates().size() == 0) {
        return;//w  ww.j  a  v  a 2  s. c  o  m
    }

    // merge dates
    SortedSet<LocalDate> existingDates = new TreeSet<LocalDate>(existingDoc.getHoliday().getHolidayDates());
    SortedSet<LocalDate> newDates = new TreeSet<LocalDate>(newDoc.getHoliday().getHolidayDates());
    List<LocalDate> result = new ArrayList<LocalDate>(newDates);
    result.addAll(0, existingDates.headSet(newDates.first()));
    result.addAll(existingDates.tailSet(newDates.last().plusYears(1).withDayOfYear(1))); // file is based on whole years

    // store into new document
    newDoc.getHoliday().getHolidayDates().clear();
    newDoc.getHoliday().getHolidayDates().addAll(result);
}

From source file:info.rmapproject.core.rmapservice.impl.openrdf.ORMapDiSCOMgr.java

/**
 * Get IRI of previous version of this DiSCO.
 *
 * @param discoID IRI of DiSCO//w ww.ja  va2 s .c o  m
 * @param event2disco Map from events to all versions of DiSCOs
 * @param date2event  Map from date events associated with version of DiSCO
 * @param ts the triplestore instance
 * @return IRI of previous version of this DiSCO, or null if none found
 * @throws RMapException the RMap exception
 * @throws RMapObjectNotFoundException the RMap object not found exception
 * @throws RMapDefectiveArgumentException the RMap defective argument exception
 */
protected IRI getPreviousIRI(IRI discoID, Map<IRI, IRI> event2disco, Map<Date, IRI> date2event,
        SesameTriplestore ts)
        throws RMapException, RMapObjectNotFoundException, RMapDefectiveArgumentException {
    if (discoID == null) {
        throw new RMapDefectiveArgumentException("null DiSCO id");
    }
    if (event2disco == null) {
        throw new RMapDefectiveArgumentException("Null event2disco map");
    }
    Map<IRI, IRI> disco2event = Utils.invertMap(event2disco);

    if (date2event == null) {
        date2event = eventmgr.getDate2EventMap(event2disco.keySet(), ts);
    }

    Map<IRI, Date> event2date = Utils.invertMap(date2event);

    IRI discoEventId = disco2event.get(discoID);
    Date eventDate = event2date.get(discoEventId);

    SortedSet<Date> sortedDates = new TreeSet<Date>();
    sortedDates.addAll(date2event.keySet());
    SortedSet<Date> earlierDates = sortedDates.headSet(eventDate);
    IRI prevDiscoId = null;
    if (earlierDates.size() > 0) {
        Date previousDate = earlierDates.last();
        IRI prevEventId = date2event.get(previousDate);
        prevDiscoId = event2disco.get(prevEventId);
    }
    return prevDiscoId;
}

From source file:com.alibaba.otter.shared.arbitrate.impl.zookeeper.lock.DistributedLock.java

/**
 * lock??watch????lock?// www.j  a v a 2s .  com
 */
private Boolean acquireLock(final BooleanMutex mutex) {
    try {
        do {
            if (id == null) {// ?lock
                long sessionId = getSessionId();
                String prefix = "x-" + sessionId + "-";
                // 
                String path = zookeeper.create(root + "/" + prefix, data, CreateMode.EPHEMERAL_SEQUENTIAL);
                int index = path.lastIndexOf("/");
                id = StringUtils.substring(path, index + 1);
                idName = new LockNode(id);
            }

            if (id != null) {
                List<String> names = zookeeper.getChildren(root);
                if (names.isEmpty()) {
                    logger.warn("lock lost with scene:empty list, id[] and node[]", id, idName);
                    unlock();// ??
                } else {
                    // ?
                    SortedSet<LockNode> sortedNames = new TreeSet<LockNode>();
                    for (String name : names) {
                        sortedNames.add(new LockNode(name));
                    }

                    if (sortedNames.contains(idName) == false) {
                        logger.warn("lock lost with scene:not contains ,id[] and node[]", id, idName);
                        unlock();// ??
                        continue;
                    }

                    // ?ownerId
                    ownerId = sortedNames.first().getName();
                    if (mutex != null && isOwner()) {
                        mutex.set(true);// ?
                        return true;
                    } else if (mutex == null) {
                        return isOwner();
                    }

                    SortedSet<LockNode> lessThanMe = sortedNames.headSet(idName);
                    if (!lessThanMe.isEmpty()) {
                        // ?
                        LockNode lastChildName = lessThanMe.last();
                        lastChildId = lastChildName.getName();
                        // watcher?
                        IZkConnection connection = zookeeper.getConnection();
                        // zkclient?zk?lock??watcher?zk?
                        ZooKeeper orginZk = ((ZooKeeperx) connection).getZookeeper();
                        Stat stat = orginZk.exists(root + "/" + lastChildId, new AsyncWatcher() {

                            public void asyncProcess(WatchedEvent event) {
                                if (!mutex.state()) { // ?????lock
                                    acquireLock(mutex);
                                } else {
                                    logger.warn("locked successful.");
                                }
                            }

                        });

                        if (stat == null) {
                            acquireLock(mutex);// ????watcher?
                        }
                    } else {
                        if (isOwner()) {
                            mutex.set(true);
                        } else {
                            logger.warn("lock lost with scene:no less ,id[] and node[]", id, idName);
                            unlock();// ?idownerId??
                        }
                    }
                }
            }
        } while (id == null);
    } catch (KeeperException e) {
        exception = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (InterruptedException e) {
        interrupt = e;
        if (mutex != null) {
            mutex.set(true);
        }
    } catch (Throwable e) {
        other = e;
        if (mutex != null) {
            mutex.set(true);
        }
    }

    if (isOwner() && mutex != null) {
        mutex.set(true);
    }
    return Boolean.FALSE;
}

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

/**
 * Test method for 'java.util.SortedSet.headSet(Object, Object)'.
 *
 * @see java.util.SortedSet#headSet(Object)
 *//*from w  w w.j a v  a 2  s  . c o m*/
@SuppressWarnings("unchecked")
public void testHeadMap_throwsClassCastException() {
    SortedSet SortedSet = createNavigableSet();
    SortedSet.add(getKeys()[0]);
    if (isNaturalOrder()) {
        // TODO Why does this succeed with natural ordering when subSet doesn't?
        SortedSet.headSet(getConflictingKey());
    } else {
        try {
            SortedSet.headSet(getConflictingKey());
            assertTrue("CCE expected in Development Mode", !TestUtils.isJvm());
        } catch (ClassCastException e) {
            // expected outcome
        }
    }
}