Example usage for java.util Collections sort

List of usage examples for java.util Collections sort

Introduction

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

Prototype

@SuppressWarnings({ "unchecked", "rawtypes" })
public static <T> void sort(List<T> list, Comparator<? super T> c) 

Source Link

Document

Sorts the specified list according to the order induced by the specified comparator.

Usage

From source file:Person.java

public static void main(String args[]) {
    ArrayList<Person> names = new ArrayList<Person>();
    names.add(new Person("E", "T"));
    names.add(new Person("A", "G"));
    names.add(new Person("B", "H"));
    names.add(new Person("C", "J"));

    Iterator iter1 = names.iterator();
    while (iter1.hasNext()) {
        System.out.println(iter1.next());
    }//from www  .ja v a2s. c  o m
    Collections.sort(names, new PersonComparator());
    Iterator iter2 = names.iterator();
    while (iter2.hasNext()) {
        System.out.println(iter2.next());
    }
}

From source file:org.lieuofs.extraction.commune.historisation.ExtractionNumHistorisationCommune.java

/**
 * @param args/*ww w.  j  av a  2s.  c  o m*/
 */
public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_lieuofs.xml" });
    CommuneCritere critere = new CommuneCritere();
    IGestionCommune gestionnaire = (IGestionCommune) context.getBean("gestionCommune");
    List<ICommuneSuisse> communes = gestionnaire.rechercher(critere);
    Collections.sort(communes, new Comparator<ICommuneSuisse>() {
        public int compare(ICommuneSuisse com1, ICommuneSuisse com2) {
            return com1.getNumeroOFS() - com2.getNumeroOFS();
        }
    });

    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("NumeroHistorisationCommune.sql"), "Windows-1252"));
    NumeroHistorisationCommuneWriter commWriter = new NumeroHistorisationRefonteSQLWriter();
    for (ICommuneSuisse commune : communes) {
        String numHistStr = commWriter.ecrireNumero(commune);
        if (null != numHistStr) {
            writer.append(numHistStr);
        }
    }
    writer.close();

}

From source file:Person.java

public static void main(String args[]) {
    ArrayList<Person> names = new ArrayList<Person>();
    names.add(new Person("E", "T"));
    names.add(new Person("A", "G"));
    names.add(new Person("B", "H"));
    names.add(new Person("C", "J"));

    Iterator iter1 = names.iterator();
    while (iter1.hasNext()) {
        System.out.println(iter1.next());
    }//from ww  w . j a va2 s . c om
    System.out.println("Before sorting");
    Collections.sort(names, new PersonComparator());
    Iterator iter2 = names.iterator();
    while (iter2.hasNext()) {
        System.out.println(iter2.next());
    }
}

From source file:at.tuwien.ifs.somtoolbox.doc.RunnablesReferenceCreator.java

public static void main(String[] args) {
    ArrayList<Class<? extends SOMToolboxApp>> runnables = SubClassFinder.findSubclassesOf(SOMToolboxApp.class,
            true);/*from  w w  w .j a v  a  2  s  . co m*/
    Collections.sort(runnables, SOMToolboxApp.TYPE_GROUPED_COMPARATOR);

    StringBuilder sbIndex = new StringBuilder(runnables.size() * 50);
    StringBuilder sbDetails = new StringBuilder(runnables.size() * 200);

    sbIndex.append("\n<table border=\"0\">\n");

    Type lastType = null;

    for (Class<? extends SOMToolboxApp> c : runnables) {
        try {
            // Ignore abstract classes and interfaces
            if (Modifier.isAbstract(c.getModifiers()) || Modifier.isInterface(c.getModifiers())) {
                continue;
            }

            Type type = Type.getType(c);
            if (type != lastType) {
                sbIndex.append("  <tr> <td colspan=\"2\"> <h5> " + type + " Applications </h5> </td> </tr>\n");
                sbDetails.append("<h2> " + type + " Applications </h2>\n");
                lastType = type;
            }
            String descr = "N/A";
            try {
                descr = (String) c.getDeclaredField("DESCRIPTION").get(null);
            } catch (Exception e) {
            }
            String longDescr = "descr";
            try {
                longDescr = (String) c.getDeclaredField("LONG_DESCRIPTION").get(null);
            } catch (Exception e) {
            }

            sbIndex.append("  <tr>\n");
            sbIndex.append("    <td> <a href=\"#").append(c.getSimpleName()).append("\">")
                    .append(c.getSimpleName()).append("</a> </td>\n");
            sbIndex.append("    <td> ").append(descr).append(" </td>\n");
            sbIndex.append("  </tr>\n");

            sbDetails.append("<h3 id=\"").append(c.getSimpleName()).append("\">").append(c.getSimpleName())
                    .append("</h3>\n");
            sbDetails.append("<p>").append(longDescr).append("</p>\n");

            try {
                Parameter[] options = (Parameter[]) c.getField("OPTIONS").get(null);
                JSAP jsap = AbstractOptionFactory.registerOptions(options);
                final ByteArrayOutputStream os = new ByteArrayOutputStream();
                PrintStream ps = new PrintStream(os);
                AbstractOptionFactory.printHelp(jsap, c.getName(), ps);
                sbDetails.append("<pre>").append(StringEscapeUtils.escapeHtml(os.toString())).append("</pre>");
            } catch (Exception e1) { // we didn't find the options => let the class be invoked ...
            }

        } catch (SecurityException e) {
            // Should not happen - no Security
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        }
    }
    sbIndex.append("</table>\n\n");
    System.out.println(sbIndex);
    System.out.println(sbDetails);
}

From source file:org.lieuofs.extraction.etatpays.ExtractionPays.java

/**
 * @param args/*from w w w .j ava  2s.  c  om*/
 */
public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_lieuofs.xml" });
    EtatTerritoireCritere critere = new EtatTerritoireCritere();
    //critere.setEstEtat(Boolean.FALSE);

    EtatTerritoireDao dao = (EtatTerritoireDao) context.getBean("etatTerritoireDao");
    Set<EtatTerritoirePersistant> etats = dao.rechercher(critere);

    EtatWriter etatWriter = new NumOFSEtatWriter();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("ExtractionPaysOFSReconnuRecemment.txt"), "UTF-8"));

    List<EtatTerritoirePersistant> listeTriee = new ArrayList<EtatTerritoirePersistant>(etats);
    Collections.sort(listeTriee, new Comparator<EtatTerritoirePersistant>() {

        @Override
        public int compare(EtatTerritoirePersistant o1, EtatTerritoirePersistant o2) {
            //return o1.getFormeCourte("fr").compareTo(o2.getFormeCourte("fr"));
            return o1.getNumeroOFS() - o2.getNumeroOFS();
        }

    });

    for (EtatTerritoirePersistant etat : filtre(listeTriee)) {
        String etatStr = etatWriter.ecrireEtat(etat);
        if (null != etatStr) {
            writer.append(etatStr);
        }
    }
    writer.close();
}

From source file:org.lieuofs.extraction.etatpays.ExtractionEtat.java

/**
 * @param args/*from w w w  . ja  v a  2  s.com*/
 */
public static void main(String[] args) throws IOException {
    ApplicationContext context = new ClassPathXmlApplicationContext(new String[] { "beans_lieuofs.xml" });
    EtatTerritoireCritere critere = new EtatTerritoireCritere();
    critere.setEstEtat(Boolean.TRUE);
    // critere.setValide(Boolean.TRUE);

    EtatTerritoireDao dao = (EtatTerritoireDao) context.getBean("etatTerritoireDao");
    Set<EtatTerritoirePersistant> etats = dao.rechercher(critere);

    EtatWriter etatWriter = new CsvPlatEtatWriter();
    BufferedWriter writer = new BufferedWriter(
            new OutputStreamWriter(new FileOutputStream("Etat.txt"), "UTF-8"));

    List<EtatTerritoirePersistant> listeTriee = new ArrayList<EtatTerritoirePersistant>(etats);
    Collections.sort(listeTriee, new Comparator<EtatTerritoirePersistant>() {

        @Override
        public int compare(EtatTerritoirePersistant o1, EtatTerritoirePersistant o2) {
            //return o1.getFormeCourte("fr").compareTo(o2.getFormeCourte("fr"));
            return o1.getNumeroOFS() - o2.getNumeroOFS();
        }

    });

    for (EtatTerritoirePersistant etat : listeTriee) {
        String etatStr = etatWriter.ecrireEtat(etat);
        if (null != etatStr) {
            writer.append(etatStr);
        }
    }
    writer.close();
}

From source file:com.pureinfo.srm.reports.table.data.sci.SCIBySchoolStatistic.java

public static void main(String[] args) throws PureException {
    IProductMgr mgr = (IProductMgr) ArkContentHelper.getContentMgrOf(Product.class);
    IStatement stat = mgr.createQuery(/* w  w  w.  jav a 2 s .c  o m*/
            "select count({this.id}) _NUM, {this.englishScience} AS _SUB from {this} group by _SUB", 0);
    IObjects nums = stat.executeQuery(false);
    DolphinObject num = null;
    Map map = new HashedMap();
    while ((num = nums.next()) != null) {
        String subest = num.getStrProperty("_SUB");
        if (subest == null || subest.trim().length() == 0)
            continue;
        String[] subs = subest.split(";");
        int nNum = num.getIntProperty("_NUM", 0);
        for (int i = 0; i < subs.length; i++) {
            String sSub = subs[i].trim();
            Integer odValue = (Integer) map.get(sSub);
            int sum = odValue == null ? nNum : (nNum + odValue.intValue());
            map.put(sSub, new Integer(sum));
        }
    }
    List l = new ArrayList(map.size());

    for (Iterator iter = map.entrySet().iterator(); iter.hasNext();) {
        Map.Entry en = (Map.Entry) iter.next();
        l.add(new Object[] { en.getKey(), en.getValue() });
    }
    Collections.sort(l, new Comparator() {

        public int compare(Object _sO1, Object _sO2) {
            Object[] arr1 = (Object[]) _sO1;
            Object[] arr2 = (Object[]) _sO2;
            Comparable s1 = (Comparable) arr1[1];
            Comparable s2 = (Comparable) arr2[01];
            return s1.compareTo(s2);
        }
    });
    for (Iterator iter = l.iterator(); iter.hasNext();) {
        Object[] arr = (Object[]) iter.next();
        System.out.println(arr[0] + " = " + arr[1]);
    }

}

From source file:edu.umd.cloud9.example.bigram.AnalyzeBigramCount.java

@SuppressWarnings({ "static-access" })
public static void main(String[] args) {
    Options options = new Options();

    options.addOption(OptionBuilder.withArgName("path").hasArg().withDescription("input path").create(INPUT));

    CommandLine cmdline = null;//from www  .  ja  va  2  s .com
    CommandLineParser parser = new GnuParser();

    try {
        cmdline = parser.parse(options, args);
    } catch (ParseException exp) {
        System.err.println("Error parsing command line: " + exp.getMessage());
        System.exit(-1);
    }

    if (!cmdline.hasOption(INPUT)) {
        System.out.println("args: " + Arrays.toString(args));
        HelpFormatter formatter = new HelpFormatter();
        formatter.setWidth(120);
        formatter.printHelp(AnalyzeBigramCount.class.getName(), options);
        ToolRunner.printGenericCommandUsage(System.out);
        System.exit(-1);
    }

    String inputPath = cmdline.getOptionValue(INPUT);
    System.out.println("input path: " + inputPath);
    List<PairOfWritables<Text, IntWritable>> bigrams = SequenceFileUtils.readDirectory(new Path(inputPath));

    Collections.sort(bigrams, new Comparator<PairOfWritables<Text, IntWritable>>() {
        public int compare(PairOfWritables<Text, IntWritable> e1, PairOfWritables<Text, IntWritable> e2) {
            if (e2.getRightElement().compareTo(e1.getRightElement()) == 0) {
                return e1.getLeftElement().compareTo(e2.getLeftElement());
            }

            return e2.getRightElement().compareTo(e1.getRightElement());
        }
    });

    int singletons = 0;
    int sum = 0;
    for (PairOfWritables<Text, IntWritable> bigram : bigrams) {
        sum += bigram.getRightElement().get();

        if (bigram.getRightElement().get() == 1) {
            singletons++;
        }
    }

    System.out.println("total number of unique bigrams: " + bigrams.size());
    System.out.println("total number of bigrams: " + sum);
    System.out.println("number of bigrams that appear only once: " + singletons);

    System.out.println("\nten most frequent bigrams: ");

    Iterator<PairOfWritables<Text, IntWritable>> iter = Iterators.limit(bigrams.iterator(), 10);
    while (iter.hasNext()) {
        PairOfWritables<Text, IntWritable> bigram = iter.next();
        System.out.println(bigram.getLeftElement() + "\t" + bigram.getRightElement());
    }
}

From source file:StrSortCase.java

/** Simple main program to test the sorting */
public static void main(String[] argv) {
    //+//from   w  w  w . j  av a 2  s. c o  m
    System.out.println("StrSort Demo Ignoring Case");
    StrSortCase s = new StrSortCase();
    s.load();
    s.dump("Before");
    Collections.sort(s.v, String.CASE_INSENSITIVE_ORDER);
    s.dump("After");
}

From source file:net.landora.justintv.JustinTVAPI.java

public static void main(String[] args) throws Exception {
    List<JustinArchive> archives = readArchives("tsmtournaments", 64);
    Map<String, List<JustinArchive>> groups = new HashMap<String, List<JustinArchive>>();
    for (int i = 0; i < archives.size(); i++) {
        JustinArchive archive = archives.get(i);
        List<JustinArchive> group = groups.get(archive.getBroadcastId());
        if (group == null) {
            group = new ArrayList<JustinArchive>(archive.getBroadcastPart());
            groups.put(archive.getBroadcastId(), group);
        }//from w  w  w  .ja  v  a2s. co  m
        group.add(archive);
    }

    BroadcastSorter sorter = new BroadcastSorter();

    for (List<JustinArchive> group : groups.values()) {
        Collections.sort(group, sorter);

        JustinArchive base = group.get(group.size() - 1);

        StringBuffer cmd = new StringBuffer();
        cmd.append("mkvmerge -o \"");
        cmd.append(base.getBroadcastId());
        cmd.append(" - ");
        cmd.append(base.getTitle());
        cmd.append("\" ");

        for (int i = 0; i < group.size(); i++) {
            JustinArchive archive = group.get(i);
            if (i > 0)
                cmd.append("+ ");

            cmd.append(archive.getId());
            cmd.append(".mkv ");
        }
        System.out.println(cmd);
    }
}