Example usage for java.util TreeSet TreeSet

List of usage examples for java.util TreeSet TreeSet

Introduction

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

Prototype

public TreeSet(SortedSet<E> s) 

Source Link

Document

Constructs a new tree set containing the same elements and using the same ordering as the specified sorted set.

Usage

From source file:Employee.java

public static void main(String args[]) {
    Employee emps[] = { new Employee("Finance", "A"), new Employee("Finance", "B"),
            new Employee("Finance", "C"), new Employee("Engineering", "D"), new Employee("Engineering", "E"),
            new Employee("Engineering", "F"), new Employee("Sales", "G"), new Employee("Sales", "H"),
            new Employee("Support", "I"), };
    Set set = new TreeSet(new EmpComparator());
    set.addAll(Arrays.asList(emps));
    System.out.println(set);//from ww  w  . jav a  2s. co  m
}

From source file:SetStuff.java

public static void main(String[] args) {

    // Create two sets.
    Set s1 = new HashSet();
    s1.add("Ian Darwin");
    s1.add("Bill Dooley");
    s1.add("Jesse James");

    Set s2 = new HashSet();
    s2.add("Ian Darwin");
    s2.add("Doolin' Dalton");

    Set union = new TreeSet(s1);
    union.addAll(s2); // now contains the union

    print("union", union);

    Set intersect = new TreeSet(s1);
    intersect.retainAll(s2);/* w w w .  j  av a  2 s . c o m*/

    print("intersection", intersect);

}

From source file:TreeSetDemo.java

public static void main(String[] argv) {
    //+//from  ww  w  .  j  av  a 2 s  .co m
    /*
     * A TreeSet keeps objects in sorted order. We use a Comparator
     * published by String for case-insensitive sorting order.
     */
    TreeSet tm = new TreeSet(String.CASE_INSENSITIVE_ORDER);
    tm.add("Gosling");
    tm.add("da Vinci");
    tm.add("van Gogh");
    tm.add("Java To Go");
    tm.add("Vanguard");
    tm.add("Darwin");
    tm.add("Darwin"); // TreeSet is Set, ignores duplicates.

    // Since it is sorted we can ask for various subsets
    System.out.println("Lowest (alphabetically) is " + tm.first());
    // Print how many elements are greater than "k"
    System.out.println(tm.tailSet("k").toArray().length + " elements higher than \"k\"");

    // Print the whole list in sorted order
    System.out.println("Sorted list:");
    java.util.Iterator t = tm.iterator();
    while (t.hasNext())
        System.out.println(t.next());
    //-
}

From source file:com.adobe.aem.demomachine.Checksums.java

public static void main(String[] args) {

    String rootFolder = null;// w w w .  j  a  v  a 2 s.c  o m

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Demo Machine root folder");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            rootFolder = cmd.getOptionValue("f");
        }

    } catch (Exception e) {
        System.exit(-1);
    }

    Properties md5properties = new Properties();
    List<String[]> listPaths = Arrays.asList(AemDemoConstants.demoPaths);
    for (String[] path : listPaths) {
        if (path.length == 5) {
            logger.debug(path[1]);
            File pathFolder = new File(rootFolder + (path[1].length() > 0 ? (File.separator + path[1]) : ""));
            if (pathFolder.exists()) {
                String md5 = AemDemoUtils.calcMD5HashForDir(pathFolder, Boolean.parseBoolean(path[3]), false);
                logger.debug("MD5 is: " + md5);
                md5properties.setProperty("demo.path." + path[0], path[1]);
                md5properties.setProperty("demo.md5." + path[0], md5);
            } else {
                logger.error("Folder cannot be found");
            }
        }
    }

    File md5 = new File(rootFolder + File.separator + "conf" + File.separator + "checksums.properties");
    try {

        @SuppressWarnings("serial")
        Properties tmpProperties = new Properties() {
            @Override
            public synchronized Enumeration<Object> keys() {
                return Collections.enumeration(new TreeSet<Object>(super.keySet()));
            }
        };
        tmpProperties.putAll(md5properties);
        tmpProperties.store(new FileOutputStream(md5), null);
    } catch (Exception e) {
        logger.error(e.getMessage());
    }

    System.out.println("MD5 checkums generated");

}

From source file:com.example.Client.java

public static void main(String[] args) throws Exception {
    // Create an RMI connector client and
    // connect it to the RMI connector server
    ///*from  w  w w .j  a  v a2  s.com*/
    echo("\nCreate an RMI connector client and " + "connect it to the RMI connector server");
    JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://:9999/jmxrmi");
    JMXConnector jmxc = JMXConnectorFactory.connect(url, null);

    // Create listener
    //
    ClientListener listener = new ClientListener();

    // Get an MBeanServerConnection
    //
    echo("\nGet an MBeanServerConnection");
    MBeanServerConnection mbsc = jmxc.getMBeanServerConnection();
    waitForEnterPressed();

    // Get domains from MBeanServer
    //
    echo("\nDomains:");
    String domains[] = mbsc.getDomains();
    Arrays.sort(domains);
    for (String domain : domains) {
        echo("\tDomain = " + domain);
    }
    waitForEnterPressed();

    // Get MBeanServer's default domain
    //
    echo("\nMBeanServer default domain = " + mbsc.getDefaultDomain());

    // Get MBean count
    //
    echo("\nMBean count = " + mbsc.getMBeanCount());

    // Query MBean names
    //
    echo("\nQuery MBeanServer MBeans:");
    Set<ObjectName> names = new TreeSet<ObjectName>(mbsc.queryNames(null, null));
    for (ObjectName name : names) {
        echo("\tObjectName = " + name);
    }
    waitForEnterPressed();

    // ----------------------
    // Manage the Hello MBean
    // ----------------------

    echo("\n>>> Perform operations on Hello MBean <<<");

    // Construct the ObjectName for the Hello MBean
    //
    ObjectName mbeanName = new ObjectName("com.example:type=Hello");

    // Create a dedicated proxy for the MBean instead of
    // going directly through the MBean server connection
    //
    HelloMBean mbeanProxy = JMX.newMBeanProxy(mbsc, mbeanName, HelloMBean.class, true);

    // Add notification listener on Hello MBean
    //
    echo("\nAdd notification listener...");
    mbsc.addNotificationListener(mbeanName, listener, null, null);

    // Get CacheSize attribute in Hello MBean
    //
    echo("\nCacheSize = " + mbeanProxy.getCacheSize());

    // Set CacheSize attribute in Hello MBean
    // Calling "reset" makes the Hello MBean emit a
    // notification that will be received by the registered
    // ClientListener.
    //
    mbeanProxy.setCacheSize(150);

    // Sleep for 2 seconds to have time to receive the notification
    //
    echo("\nWaiting for notification...");
    sleep(2000);

    // Get CacheSize attribute in Hello MBean
    //
    echo("\nCacheSize = " + mbeanProxy.getCacheSize());

    // Invoke "sayHello" in Hello MBean
    //
    echo("\nInvoke sayHello() in Hello MBean...");
    mbeanProxy.sayHello();

    // Invoke "add" in Hello MBean
    //
    echo("\nInvoke add(2, 3) in Hello MBean...");
    echo("\nadd(2, 3) = " + mbeanProxy.add(2, 3));

    waitForEnterPressed();

    // ------------------------------
    // Manage the QueueSampler MXBean
    // ------------------------------

    echo("\n>>> Perform operations on QueueSampler MXBean <<<");

    // Construct the ObjectName for the QueueSampler MXBean
    //
    ObjectName mxbeanName = new ObjectName("com.example:type=QueueSampler");

    // Create a dedicated proxy for the MXBean instead of
    // going directly through the MBean server connection
    //
    QueueSamplerMXBean mxbeanProxy = JMX.newMXBeanProxy(mbsc, mxbeanName, QueueSamplerMXBean.class);

    // Get QueueSample attribute in QueueSampler MXBean
    //
    QueueSample queue1 = mxbeanProxy.getQueueSample();
    echo("\nQueueSample.Date = " + queue1.getDate());
    echo("QueueSample.Head = " + queue1.getHead());
    echo("QueueSample.Size = " + queue1.getSize());

    // Invoke "clearQueue" in QueueSampler MXBean
    //
    echo("\nInvoke clearQueue() in QueueSampler MXBean...");
    mxbeanProxy.clearQueue();

    // Get QueueSample attribute in QueueSampler MXBean
    //
    QueueSample queue2 = mxbeanProxy.getQueueSample();
    echo("\nQueueSample.Date = " + queue2.getDate());
    echo("QueueSample.Head = " + queue2.getHead());
    echo("QueueSample.Size = " + queue2.getSize());

    waitForEnterPressed();

    // Close MBeanServer connection
    //
    echo("\nClose the connection to the server");
    jmxc.close();
    echo("\nBye! Bye!");
}

From source file:com.edgenius.wiki.render.handler.MenuMacroHandler.java

public static void main(String[] args) {
    RenderContextImpl context = new RenderContextImpl();
    LinkRenderHelperImpl linkRenderHelper = new LinkRenderHelperImpl();
    linkRenderHelper.initialize(context, null, null);

    context.setLinkRenderHelper(linkRenderHelper);
    MenuMacroHandler h = new MenuMacroHandler();
    Set<MenuItem> menuItems = new TreeSet<MenuItem>(new MenuItem.MenuItemComparator());
    MenuItem m1 = new MenuItem();
    m1.setTitle("m1");
    m1.setPageTitle("t1");
    m1.setPageUuid("pm1");

    MenuItem m2 = new MenuItem();
    m2.setTitle("m2");
    m2.setPageTitle("t2");
    m2.setPageUuid("pm2");

    MenuItem m21 = new MenuItem();
    m21.setTitle("m21");
    m21.setPageUuid("pm21");
    m21.setPageTitle("t21");
    m21.setParent("pm2");

    MenuItem m22 = new MenuItem();
    m22.setTitle("m22");
    m22.setPageUuid("pm22");
    m22.setPageTitle("t22");
    m22.setParent("pm2");

    MenuItem m221 = new MenuItem();
    m221.setTitle("m221");
    m221.setPageTitle("t221");
    m221.setPageUuid("pm221");
    m221.setParent("pm22");

    MenuItem m222 = new MenuItem();
    m222.setTitle("m222");
    m222.setPageTitle("t222");
    m222.setPageUuid("pm222");
    m222.setParent("pm22");

    MenuItem m3 = new MenuItem();
    m3.setTitle("m3");
    m3.setPageTitle("t2");
    m3.setPageUuid("pm3");

    menuItems.add(m1);/*from  w  ww.j a  va2 s  .com*/
    menuItems.add(m2);
    menuItems.add(m21);
    menuItems.add(m22);
    menuItems.add(m221);
    menuItems.add(m222);
    menuItems.add(m3);

    System.out.println(h.buildMenu(context, menuItems));
}

From source file:com.curecomp.primefaces.migrator.PrimefacesMigration.java

public static void main(String[] args) throws Exception {
    // Let's use some colors :)
    //        AnsiConsole.systemInstall();
    CommandLineParser cliParser = new BasicParser();
    CommandLine cli = null;/*from  ww  w.  j  ava  2  s . co  m*/
    try {
        cli = cliParser.parse(OPTIONS, args);
    } catch (ParseException e) {
        printHelp();
    }
    if (!cli.hasOption("s")) {
        printHelp();
    }

    String sourcePattern;
    if (cli.hasOption("p")) {
        sourcePattern = cli.getOptionValue("p");
    } else {
        sourcePattern = DEFAULT_SOURCE_PATTERN;
    }

    String defaultAnswer;
    if (cli.hasOption("default-answer")) {
        defaultAnswer = cli.getOptionValue("default-answer");
    } else {
        defaultAnswer = DEFAULT_DEFAULT_PROMPT_ANSWER;
    }

    boolean defaultAnswerYes = defaultAnswer.equalsIgnoreCase("y");
    boolean quiet = cli.hasOption("q");
    boolean testWrite = cli.hasOption("t");
    Path sourceDirectory = Paths.get(cli.getOptionValue("s")).toAbsolutePath();
    // Since we use IO we will have some blocking threads hanging around
    int threadCount = Runtime.getRuntime().availableProcessors() * 2;
    ThreadPoolExecutor threadPool = new ThreadPoolExecutor(threadCount, threadCount, 0L, TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>());
    BlockingQueue<WidgetVarLocation> foundUsages = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> unusedOrAmbiguous = new LinkedBlockingQueue<>();
    BlockingQueue<WidgetVarLocation> skippedUsages = new LinkedBlockingQueue<>();
    List<Future<?>> futures = new ArrayList<>();

    findWidgetVars(sourceDirectory, sourcePattern, threadPool).forEach(widgetVarLocation -> {
        // We can't really find usages of widget vars that use EL expressions :(
        if (widgetVarLocation.widgetVar.contains("#")) {
            unusedOrAmbiguous.add(widgetVarLocation);
            return;
        }

        try {
            FileActionVisitor visitor = new FileActionVisitor(sourceDirectory, sourcePattern,
                    sourceFile -> futures.add(threadPool.submit((Callable<?>) () -> {
                        findWidgetVarUsages(sourceFile, widgetVarLocation, foundUsages, skippedUsages,
                                unusedOrAmbiguous);
                        return null;
                    })));

            Files.walkFileTree(sourceDirectory, visitor);
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }
    });

    awaitAll(futures);

    new TreeSet<>(skippedUsages).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped " + relativePath + " at line " + widgetUsage.lineNr + " and col "
                + widgetUsage.columnNr + " for widgetVar '" + widgetUsage.widgetVar + "'");
        System.out.println("\t" + previous);
    });

    Map<WidgetVarLocation, List<WidgetVarLocation>> written = new HashMap<>();

    new TreeSet<>(foundUsages).forEach(widgetUsage -> {
        WidgetVarLocation key = new WidgetVarLocation(null, widgetUsage.location, widgetUsage.lineNr, -1, null);
        List<WidgetVarLocation> writtenList = written.get(key);
        int existing = writtenList == null ? 0 : writtenList.size();
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String next = replace(widgetUsage.line, startIndex, endIndex, Ansi.ansi().bold().fg(Ansi.Color.RED)
                .a("PF('" + widgetUsage.widgetVar + "')").reset().toString());
        System.out
                .println(relativePath + " at line " + widgetUsage.lineNr + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + next);
        System.out.print("Replace (Y/N)? [" + (defaultAnswerYes ? "Y" : "N") + "]: ");

        String input;

        if (quiet) {
            input = "";
            System.out.println();
        } else {
            try {
                do {
                    input = in.readLine();
                } while (input != null && !input.isEmpty() && !"y".equalsIgnoreCase(input)
                        && !"n".equalsIgnoreCase(input));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        }

        if (input == null) {
            System.out.println("Aborted!");
        } else if (input.isEmpty() && defaultAnswerYes || !input.isEmpty() && !"n".equalsIgnoreCase(input)) {
            System.out.println("Replaced!");
            System.out.print("\t");
            if (writtenList == null) {
                writtenList = new ArrayList<>();
                written.put(key, writtenList);
            }

            writtenList.add(widgetUsage);
            List<String> lines;
            try {
                lines = Files.readAllLines(widgetUsage.location);
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }

            try (OutputStream os = testWrite ? new ByteArrayOutputStream()
                    : Files.newOutputStream(widgetUsage.location);
                    PrintWriter pw = new PrintWriter(new OutputStreamWriter(os, StandardCharsets.UTF_8))) {
                String line;

                for (int i = 0; i < lines.size(); i++) {
                    int lineNr = i + 1;
                    line = lines.get(i);

                    if (lineNr == widgetUsage.lineNr) {
                        int begin = widgetUsage.columnNr + (testWrite ? 0 : existing * 6);
                        int end = begin + widgetUsage.widgetVar.length();
                        String newLine = replace(line, begin, end, "PF('" + widgetUsage.widgetVar + "')",
                                false);

                        if (testWrite) {
                            System.out.println(newLine);
                        } else {
                            pw.println(newLine);
                        }
                    } else {
                        if (!testWrite) {
                            pw.println(line);
                        }
                    }
                }
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        } else {
            System.out.println("Skipped!");
        }
    });

    new TreeSet<>(unusedOrAmbiguous).forEach(widgetUsage -> {
        int startIndex = widgetUsage.columnNr;
        int endIndex = startIndex + widgetUsage.widgetVar.length();
        String relativePath = widgetUsage.location.toAbsolutePath().toString()
                .substring(sourceDirectory.toString().length());
        String previous = replace(widgetUsage.line, startIndex, endIndex,
                Ansi.ansi().bold().fg(Ansi.Color.RED).a(widgetUsage.widgetVar).reset().toString());
        System.out.println("Skipped unused or ambiguous " + relativePath + " at line " + widgetUsage.lineNr
                + " and col " + widgetUsage.columnNr);
        System.out.println("\t" + previous);
    });

    threadPool.shutdown();
}

From source file:com.jslsolucoes.tagria.doc.generator.DocGenerator.java

public static void main(String[] args) throws IOException {

    String workspace = args[0];// w w  w .  java 2  s .  co  m
    Map<String, List<Tag>> groupments = new HashMap<>();

    String html = FileUtils.readFileToString(
            new File(workspace + "/tagria-lib/src/main/resources/META-INF/html.tld"), CHARSET);
    String ajax = FileUtils.readFileToString(
            new File(workspace + "/tagria-lib/src/main/resources/META-INF/ajax.tld"), CHARSET);
    XStream xStream = new XStream();
    xStream.processAnnotations(Taglib.class);
    Taglib taglibForHtml = (Taglib) xStream.fromXML(html);
    Taglib taglibForAjax = (Taglib) xStream.fromXML(ajax);
    List<Tag> tags = new ArrayList<Tag>();
    tags.addAll(taglibForHtml.getTags());
    tags.addAll(taglibForAjax.getTags());

    for (Tag tag : tags) {

        List<Tag> groups = groupments.get(tag.getGroup());
        if (groups == null) {
            groupments.put(tag.getGroup(), new ArrayList<>());
        }
        groupments.get(tag.getGroup()).add(tag);

        StringBuilder template = new StringBuilder(
                "<%@include file=\"../app/taglibs.jsp\"%>                              "
                        + "<html:view title=\"{title}\">                                 "
                        + "                  <html:panel>                                                      "
                        + "                     <html:panelHead label=\"" + tag.getName()
                        + "\"></html:panelHead>               "
                        + "                     <html:panelBody>                                                "
                        + "                        <html:tabPanel>                                                "
                        + "                           <html:tab label=\"{about}\" active=\"true\">                     "
                        + "                              <html:alert state=\"warning\">                              "
                        + "                                      " + tag.getDescription()
                        + "                           "
                        + "                              </html:alert>                                          "
                        + "                           </html:tab>                                                "
                        + "                           <html:tab label=\"{attributes}\">                              ");

        if (CollectionUtils.isEmpty(tag.getAttributes())) {
            template.append("<html:alert state=\"info\" label=\"{tag.empty.attributes}\"></html:alert>");
        } else {

            template.append("<html:table><html:tableLine>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.attribute\"/></html:tableColumn>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.required\"/></html:tableColumn>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.type\"/></html:tableColumn>"
                    + "<html:tableColumn header=\"true\"><fmt:message key=\"tag.description\"/></html:tableColumn>"
                    +

                    "</html:tableLine>");

            for (Attribute attribute : tag.getAttributes()) {

                template.append("<html:tableLine>" + "<html:tableColumn>" + attribute.getName()
                        + "</html:tableColumn>" + "<html:tableColumn>"
                        + (attribute.getRequired() == null ? false : true) + "</html:tableColumn>"
                        + "<html:tableColumn>" + attribute.getType() + "</html:tableColumn>"
                        + "<html:tableColumn>" + attribute.getDescription() + "</html:tableColumn>" +

                        "</html:tableLine>");
            }

            template.append("</html:table>");
        }

        template.append("                                                                        "
                + "                           </html:tab>                                                "
                + "                           <html:tab label=\"{demo}\">                                    "
                + "                              " + tag.getExample()
                + "                                          "
                + "                           </html:tab>                                                "
                + "                           <html:tab label=\"{source}\">                                 "
                + "                              <html:code>                                             "
                + "                                 &lt;html:view&gt;" + tag.getExampleEscaped()
                + "&lt;/html:view&gt;                                 "
                + "                              </html:code>                                          "
                + "                           </html:tab>                                                "
                + "                        </html:tabPanel>                                             "
                + "                     </html:panelBody>                                                "
                + "                  </html:panel>                                                      "
                + "               </html:view>                                                         ");
        FileUtils.writeStringToFile(new File(
                workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/component/" + tag.getName() + ".jsp"),
                template.toString(), CHARSET);
    }

    for (List<Tag> values : groupments.values()) {
        Collections.sort(values, new Comparator<Tag>() {
            @Override
            public int compare(Tag o1, Tag o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
    }

    StringBuilder menu = new StringBuilder("<html:div cssClass=\"menu\"><html:listGroup>");
    for (String key : new TreeSet<String>(groupments.keySet())) {
        menu.append("<html:listGroupItem><html:collapsable label=\"" + key + "\"><html:listGroup>");
        for (Tag tag : groupments.get(key)) {
            menu.append("<html:listGroupItem><html:link label=\"" + StringUtils.capitalize(tag.getName())
                    + "\" target=\"conteudo\" url=\"/component/" + tag.getName()
                    + "\"></html:link></html:listGroupItem>");
        }
        menu.append("</html:listGroup></html:collapsable></html:listGroupItem>");
    }
    menu.append("</html:listGroup></html:div>");

    File home = new File(workspace + "/tagria-doc/src/main/webapp/WEB-INF/jsp/app/index.jsp");
    FileUtils.writeStringToFile(home, FileUtils.readFileToString(home, CHARSET)
            .replaceAll("<html:div cssClass=\"menu\">[\\s\\S]*?</html:div>", menu.toString()), CHARSET);

}

From source file:Main.java

public static <T> Set<T> union(Set<T> setA, Set<T> setB) {
    Set<T> tmp = new TreeSet<T>(setA);
    tmp.addAll(setB);//  w ww.j  a v  a 2s .c  o m
    return tmp;
}

From source file:Main.java

public static <K> SortedSet<K> newSortedSet() {
    return new TreeSet(Collator.getInstance());
}