Example usage for java.util Comparator comparing

List of usage examples for java.util Comparator comparing

Introduction

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

Prototype

public static <T, U extends Comparable<? super U>> Comparator<T> comparing(
        Function<? super T, ? extends U> keyExtractor) 

Source Link

Document

Accepts a function that extracts a java.lang.Comparable Comparable sort key from a type T , and returns a Comparator that compares by that sort key.

Usage

From source file:Main.java

public static void main(String[] args) {
    Comparator<String> keyComparator = Comparator.comparing(String::length)
            .thenComparing(String::compareToIgnoreCase);

    SortedMap<String, String> sMap = new TreeMap<>(keyComparator);
    sMap.put("CSS", "style");
    sMap.put("HTML", "mark up");
    sMap.put("Oracle", "database");
    sMap.put("XML", "data");

    SortedMap<String, String> subMap = sMap.subMap("CSS", "XML");
    System.out.println(subMap);// w  w w .j  ava  2s. com

    // Get the first and last keys
    String firstKey = sMap.firstKey();
    String lastKey = sMap.lastKey();
    System.out.println("First Key:  " + firstKey);
    System.out.println("Last key:   " + lastKey);
}

From source file:Main.java

public static void main(String[] args) {
    SortedSet<Person> personsById = new TreeSet<>(Comparator.comparing(Person::getId));

    personsById.add(new Person(1, "X"));
    personsById.add(new Person(2, "Z"));
    personsById.add(new Person(3, "A"));
    personsById.add(new Person(4, "C"));
    personsById.add(new Person(4, "S")); // A duplicate Person

    System.out.println("Persons by  Id:");
    personsById.forEach(System.out::println);

    SortedSet<Person> personsByName = new TreeSet<>(Comparator.comparing(Person::getName));
    personsByName.add(new Person(1, "X"));
    personsByName.add(new Person(2, "Z"));
    personsByName.add(new Person(3, "A"));
    personsByName.add(new Person(4, "C"));

    System.out.println("Persons by  Name: ");
    personsByName.forEach(System.out::println);

}

From source file:Main.java

public static void main(String[] args) {
    // Sort the names based on their length, placing null first
    SortedSet<String> names = new TreeSet<>(Comparator.nullsFirst(Comparator.comparing(String::length)));
    names.add("XML");
    names.add("CSS");
    names.add("HTML");
    names.add(null); // Adds a null

    // Print the names
    names.forEach(System.out::println);

}

From source file:Main.java

public static void main(String[] args) {
    List<Person> people = new ArrayList<Person>();
    people.add(new Person("C", 21));
    people.add(new Person("T", 20));
    people.add(new Person("B", 35));
    people.add(new Person("A", 22));
    people.sort(Comparator.comparing(Person::getName));
    people.forEach(System.out::println);
}

From source file:Main.java

public static void main(String[] args) {
    List<String> list = new ArrayList<>();
    list.add("Java");
    list.add("R");
    list.add("CSS");
    list.add("XML");

    System.out.println("List: " + list);

    // Uses List.sort() method with a Comparator
    list.sort(Comparator.comparing(String::length));

    System.out.println("Sorted List:  " + list);

}

From source file:Main.java

public static void main(String... args) {
    Student raoul = new Student("Raoul", "Cambridge");
    Student mario = new Student("Mario", "Milan");
    Student alan = new Student("Alan", "Cambridge");
    Student brian = new Student("Brian", "Cambridge");

    List<Graduate> transactions = Arrays.asList(new Graduate(brian, 2011, 300), new Graduate(raoul, 2012, 1000),
            new Graduate(raoul, 2011, 400), new Graduate(mario, 2012, 710), new Graduate(mario, 2012, 700),
            new Graduate(alan, 2012, 950));

    List<Graduate> tr2011 = transactions.stream().filter(transaction -> transaction.getYear() == 2011)
            .sorted(Comparator.comparing(Graduate::getValue)).collect(Collectors.toList());
    System.out.println(tr2011);/*  w w w .  j  a v  a  2  s .co m*/

}

From source file:Main.java

public static void main(String... args) {
    Student raoul = new Student("Raoul", "Cambridge");
    Student mario = new Student("Mario", "Milan");
    Student alan = new Student("Alan", "Cambridge");
    Student brian = new Student("Brian", "Cambridge");

    List<Graduate> transactions = Arrays.asList(new Graduate(brian, 2011, 300), new Graduate(raoul, 2012, 1000),
            new Graduate(raoul, 2011, 400), new Graduate(mario, 2012, 710), new Graduate(mario, 2012, 700),
            new Graduate(alan, 2012, 950));

    // Get all students from Cambridge and sort them by name.

    List<Student> traders = transactions.stream().map(Graduate::getTrader)
            .filter(trader -> trader.getCity().equals("Cambridge")).distinct()
            .sorted(Comparator.comparing(Student::getName)).collect(Collectors.toList());
    System.out.println(traders);/*from  w  w  w  . j  a  v  a  2  s .c om*/

}

From source file:ComparablePerson.java

public static void main(String[] args) {
    int initialCapacity = 5;
    Comparator<ComparablePerson> nameComparator = Comparator.comparing(ComparablePerson::getName);

    Queue<ComparablePerson> pq = new PriorityQueue<>(initialCapacity, nameComparator);
    pq.add(new ComparablePerson(1, "Oracle"));
    pq.add(new ComparablePerson(4, "XML"));
    pq.add(new ComparablePerson(2, "HTML"));
    pq.add(new ComparablePerson(3, "CSS"));
    pq.add(new ComparablePerson(4, "Java"));

    System.out.println("Priority  queue: " + pq);

    while (pq.peek() != null) {
        System.out.println("Head  Element: " + pq.peek());
        pq.remove();/* www.  j a  v a 2 s . c o m*/
        System.out.println("Removed one  element from  Queue");
        System.out.println("Priority  queue: " + pq);
    }
}

From source file:defaultmethods.StandardDeck.java

public static void main(String... args) {
    StandardDeck myDeck = new StandardDeck();
    System.out.println("Creating deck:");
    myDeck.sort();//from  w ww  .j  a  v  a 2 s .  co  m
    System.out.println("Sorted deck");
    System.out.println(myDeck.deckToString());
    myDeck.shuffle();
    myDeck.sort(new SortByRankThenSuit());
    System.out.println("Sorted by rank, then by suit");
    System.out.println(myDeck.deckToString());
    myDeck.shuffle();
    myDeck.sort(Comparator.comparing(Card::getRank).thenComparing(Comparator.comparing(Card::getSuit)));
    System.out.println("Sorted by rank, then by suit " + "with static and default methods");
    System.out.println(myDeck.deckToString());
    myDeck.sort(
            Comparator.comparing(Card::getRank).reversed().thenComparing(Comparator.comparing(Card::getSuit)));
    System.out.println("Sorted by rank reversed, then by suit " + "with static and default methods");
    System.out.println(myDeck.deckToString());
}

From source file:org.deeplearning4j.examples.unsupervised.sequenceanomalydetection.SequenceAnomalyDetection.java

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

    String dataPath = new ClassPathResource("/anomalysequencedata").getFile().getPath();
    File modelFile = new File(dataPath + File.separatorChar + "anomalyDetectionModel.gz");
    DataSetIterator trainIterator = new AnomalyDataSetIterator(dataPath + File.separatorChar + "ads.csv",
            trainBatchSize);//from w  w  w  .j  a va2 s . c  o  m
    DataSetIterator testIterator = new AnomalyDataSetIterator(dataPath + File.separatorChar + "test.csv",
            testBatchSize);

    MultiLayerNetwork net = true ? createModel(trainIterator.inputColumns(), trainIterator.totalOutcomes())
            : MultiLayerNetwork.load(modelFile, true);
    UIServer uiServer = UIServer.getInstance();
    StatsStorage statsStorage = new FileStatsStorage(
            new File(System.getProperty("java.io.tmpdir"), "ui-stats.dl4j"));
    uiServer.attach(statsStorage);

    DataNormalization normalizer = new NormalizerStandardize();
    normalizer.fit(trainIterator); //Collect training data statistics
    trainIterator.reset();
    trainIterator.setPreProcessor(normalizer);
    testIterator.setPreProcessor(normalizer); //Note: using training normalization statistics
    NormalizerSerializer.getDefault().write(normalizer,
            dataPath + File.separatorChar + "anomalyDetectionNormlizer.ty");

    // training
    net.setListeners(new StatsListener(statsStorage), new ScoreIterationListener(10));
    net.fit(trainIterator, numEpochs);

    // save model to disk
    ModelSerializer.writeModel(net, modelFile, true);

    List<Pair<Double, String>> evalList = new ArrayList<>();
    Queue<String> queue = ((AnomalyDataSetIterator) testIterator).getCurrentLines();
    double totalScore = 0;
    while (testIterator.hasNext()) {
        DataSet ds = testIterator.next();
        double score = net.score(ds);
        String currentLine = queue.poll();
        totalScore += score;
        evalList.add(new ImmutablePair<>(score, currentLine));
    }

    Collections.sort(evalList, Comparator.comparing(Pair::getLeft));
    Stack<String> anomalyData = new Stack<>();
    double threshold = totalScore / evalList.size();
    for (Pair<Double, String> pair : evalList) {
        double s = pair.getLeft();
        if (s > threshold) {
            anomalyData.push(pair.getRight());
        }
    }

    //output anomaly data
    System.out.println("based on the score, all anomaly data is following with descending order:\n");
    for (int i = anomalyData.size(); i > 0; i--) {
        System.out.println(anomalyData.pop());
    }

}