Пример #1
0
 void setServlets(List<Servlet> servlets) {
   this.servlets = servlets;
   servlets.sort(
       Comparator.<Servlet>comparingInt(
           s -> {
             Servlet.Priority priority = s.getClass().getAnnotation(Servlet.Priority.class);
             return priority == null ? 0 : priority.value();
           }));
 }
Пример #2
0
 public void testMinBy() {
   Comparator<People> cmp = Comparator.comparing(People::getFirstName);
   // lesser
   assertSame(minBy(cmp).apply(people[0], people[1]), people[0]);
   // euqal
   cmp = Comparator.comparing(People::getLastName);
   assertSame(minBy(cmp).apply(people[0], people[1]), people[0]);
   // greater
   cmp = Comparator.comparingInt(People::getAge);
   assertSame(minBy(cmp).apply(people[0], people[1]), people[1]);
 }
Пример #3
0
  @Test
  public void testCollectors() {

    ArrayList<Person> people = new ArrayList<>();
    ArrayList<Integer> things = new ArrayList<>();
    ArrayList<Employee> employees = new ArrayList<>();
    ArrayList<Student> students = new ArrayList<>();

    // Accumulate names into a List
    List<String> list = people.stream().map(Person::getName).collect(Collectors.toList());

    // Accumulate names into a TreeSet
    Set<String> list2 =
        people.stream().map(Person::getName).collect(Collectors.toCollection(TreeSet::new));

    // Convert elements to strings and concatenate them, separated by commas
    String joined = things.stream().map(Object::toString).collect(Collectors.joining(", "));

    // Find highest-paid employee
    Optional<Employee> highestPaid =
        employees.stream().collect(Collectors.maxBy(Comparator.comparingInt(Employee::getSalary)));

    // Group employees by department
    Map<Department, List<Employee>> byDept =
        employees.stream().collect(Collectors.groupingBy(Employee::getDepartment));

    // Find highest-paid employee by department
    Map<Department, Optional<Employee>> highestPaidByDept =
        employees
            .stream()
            .collect(
                Collectors.groupingBy(
                    Employee::getDepartment,
                    Collectors.maxBy(Comparator.comparingInt(Employee::getSalary))));

    // Partition students into passing and failing
    Map<Boolean, List<Student>> passingFailing =
        students.stream().collect(Collectors.partitioningBy(s -> s.getGrade() >= PASS_THRESHOLD));
  }
Пример #4
0
 @Benchmark
 public void parallel_lazy_jdk() {
   Map<Alphagram, List<String>> groupBy =
       this.guavaWords.parallelStream().collect(Collectors.groupingBy(Alphagram::new));
   groupBy
       .entrySet()
       .parallelStream()
       .map(Map.Entry::getValue)
       .filter(list -> list.size() >= SIZE_THRESHOLD)
       .sorted(Comparator.<List<String>>comparingInt(List::size).reversed())
       .map(list -> list.size() + ": " + list)
       .forEach(e -> Assert.assertFalse(e.isEmpty()));
 }
Пример #5
0
 /** Modify exercise6 so that the words are sorted by length */
 private void exercise7() throws IOException {
   try (BufferedReader reader =
       Files.newBufferedReader(getPath("Sonnetl.txt"), StandardCharsets.UTF_8)) {
     reader
         .lines()
         .flatMap(WORD_PATTERN::splitAsStream)
         .map(word -> word.toLowerCase())
         //              .sorted((s1, s2) -> s1.length() - s2.length())
         .sorted(Comparator.comparingInt(String::length))
         .distinct()
         .forEach(System.out::println);
   }
 }
 @Benchmark
 public void serial_lazy_streams_ec() {
   Map<Alphagram, Set<String>> groupBy =
       this.ecWords
           .stream()
           .collect(Collectors.groupingBy(Alphagram::new, Collectors.<String>toSet()));
   groupBy
       .entrySet()
       .stream()
       .map(Map.Entry::getValue)
       .filter(list -> list.size() >= SIZE_THRESHOLD)
       .sorted(Comparator.<Set<String>>comparingInt(Set::size).reversed())
       .map(list -> list.size() + ": " + list)
       .forEach(e -> Assert.assertFalse(e.isEmpty()));
 }
Пример #7
0
  private void orderMoves(Move[] moves, int numberOfMoves) {
    TableEntry tableEntry = transpositionTable.get(pos.key);

    for (int i = 0; i < numberOfMoves; i++) {
      Move move = moves[i];
      if (tableEntry != null) {
        if (move.from == tableEntry.getFrom() && move.to == tableEntry.getTo()) {
          move.ordering += 10000;
        }
      }
      if (move.capturedPiece != PieceType.None) {
        move.ordering += move.capturedPiece.getValue();
      }
    }
    Arrays.sort(moves, 0, numberOfMoves, Comparator.comparingInt(m -> m.ordering));
  }
Пример #8
0
  @Test
  public void testMaxAll() {
    List<String> input = Arrays.asList("a", "bb", "c", "", "cc", "eee", "bb", "ddd");
    checkCollector(
        "maxAll",
        Arrays.asList("eee", "ddd"),
        input::stream,
        MoreCollectors.maxAll(Comparator.comparingInt(String::length)));
    Collector<String, ?, String> maxAllJoin =
        MoreCollectors.maxAll(Comparator.comparingInt(String::length), Collectors.joining(","));
    checkCollector("maxAllJoin", "eee,ddd", input::stream, maxAllJoin);
    checkCollector(
        "minAll",
        1L,
        input::stream,
        MoreCollectors.minAll(Comparator.comparingInt(String::length), Collectors.counting()));
    checkCollector(
        "minAllEmpty",
        Arrays.asList(""),
        input::stream,
        MoreCollectors.minAll(Comparator.comparingInt(String::length)));
    checkCollectorEmpty(
        "maxAll",
        Collections.emptyList(),
        MoreCollectors.maxAll(Comparator.comparingInt(String::length)));
    checkCollectorEmpty("maxAllJoin", "", maxAllJoin);

    List<Integer> ints = IntStreamEx.of(new Random(1), 10000, 1, 1000).boxed().toList();
    List<Integer> expectedMax = getMaxAll(ints, Comparator.naturalOrder());
    List<Integer> expectedMin = getMaxAll(ints, Comparator.reverseOrder());
    Collector<Integer, ?, SimpleEntry<Integer, Long>> downstream =
        MoreCollectors.pairing(
            MoreCollectors.first(),
            Collectors.counting(),
            (opt, cnt) -> new AbstractMap.SimpleEntry<>(opt.get(), cnt));

    checkCollector("maxAll", expectedMax, ints::stream, MoreCollectors.maxAll(Integer::compare));
    checkCollector("minAll", expectedMin, ints::stream, MoreCollectors.minAll());
    checkCollector(
        "entry",
        new SimpleEntry<>(expectedMax.get(0), (long) expectedMax.size()),
        ints::stream,
        MoreCollectors.maxAll(downstream));
    checkCollector(
        "entry",
        new SimpleEntry<>(expectedMin.get(0), (long) expectedMin.size()),
        ints::stream,
        MoreCollectors.minAll(downstream));

    Integer a = new Integer(1), b = new Integer(1), c = new Integer(1000), d = new Integer(1000);
    ints = IntStreamEx.range(10, 100).boxed().append(a, c).prepend(b, d).toList();
    for (StreamExSupplier<Integer> supplier : streamEx(ints::stream)) {
      List<Integer> list = supplier.get().collect(MoreCollectors.maxAll());
      assertEquals(2, list.size());
      assertSame(d, list.get(0));
      assertSame(c, list.get(1));

      list = supplier.get().collect(MoreCollectors.minAll());
      assertEquals(2, list.size());
      assertSame(b, list.get(0));
      assertSame(a, list.get(1));
    }
  }
 private List<? extends Statement> getOrderedStatements(final List<? extends Statement> stats) {
   final List<? extends Statement> statList = new ArrayList<>(stats);
   statList.sort(Comparator.comparingInt(Node::getSourceOrder));
   return statList;
 }