public void writeTasks(OutputStream output) { try { output.write("[\n".getBytes()); boolean needComma = false; File[] files = tasksDirectory.listFiles((FileFilter) FileFilterUtils.directoryFileFilter()); List<Integer> numbers = new ArrayList<>(); for (File directory : files) { try { numbers.add(Integer.valueOf(directory.getName())); } catch (Throwable ignored) { } } numbers.sort(Comparator.<Integer>reverseOrder()); numbers = numbers.subList(0, Math.min(100, numbers.size())); for (int taskId : numbers) { File infoFile = new File(new File(tasksDirectory, String.valueOf(taskId)), "info.json"); if (!infoFile.exists()) { continue; } if (needComma) { output.write(",\n".getBytes()); } else { needComma = true; } try (FileInputStream fis = new FileInputStream(infoFile)) { IOUtils.copy(fis, output); } } output.write("]\n".getBytes()); } catch (IOException e) { throw Throwables.propagate(e); } }
public static void main(String[] args) { Personne[] tab = { new Personne("thibault", "Rougier", 2001), new Personne("thomas", "Niesseron", 1987), new Personne("thifaine", "Mitenne", 1959), new Personne("maxime", "Forest", 1995), new Personne("jules", "Forest", 1995) }; System.out.println("--- Nes apres 1985 : "); Stream.of(tab) .filter(pp -> pp.getAnnee() > 1985) .forEach(pp -> System.out.print(pp.getPrenom() + ", ")); System.out.println("\n--- Nes avant 2000 :"); long nombre = Stream.of(tab) .filter(pp -> pp.getAnnee() < 2000) .sorted(Comparator.comparing(Personne::getNom)) .peek(pp -> System.out.print(pp.getNom() + " ")) .count(); System.out.println("\n Ils sont " + nombre); System.out.println("--- Tous tries sur nom + prenom : "); Stream.of(tab) .sorted(Comparator.comparing(pp -> pp.getNom() + pp.getPrenom())) .forEach(pp -> System.out.print("(" + pp.getNom() + ", " + pp.getPrenom() + ") ")); }
public TestResult matchMessage(String actual, String expected) { if (actual == null) return TestResult.fail("NULL"); if (actual.equals(replaceSymbols(expected))) return TestResult.pass(replaceSymbolsWithFullExpansion(expected)); Comparator c = new Comparator(actual, expected); return c.evaluate(); }
/** * Either adds a value to set or does nothing if value is already present. * * @param val Value to add. * @return The instance of value from this set or {@code null} if value was added. */ @Nullable public V addx(V val) { A.notNull(val, "val"); if (comp == null) { for (V v : vals) if (v.equals(val)) return v; vals.add(val); return null; } if (strict) { for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); // Prefer equals to comparator. if (v.equals(val)) return v; int c = comp.compare(v, val); if (c == 0) throw new IllegalStateException("Inconsistent equals and compare methods."); if (c > 0) { // Back up. it.previous(); it.add(val); return null; } } vals.add(val); return null; } // Full scan first. for (V v : vals) if (v.equals(val)) return v; for (ListIterator<V> it = vals.listIterator(); it.hasNext(); ) { V v = it.next(); if (comp.compare(v, val) > 0) { do { // Back up. v = it.previous(); } while (comp.compare(v, val) == 0); it.add(val); return null; } } vals.add(val); return null; }
private Node<T, V> insertTree(Node<T, V> subTree, T t, V v) // called by public void insert(T t) { // insert to a subtree and return the reference of this subtree Node<T, V> ansNode = null; if (subTree == null) { ansNode = new Node<T, V>(t, v); ansNode.leftChild = null; ansNode.rightChild = null; ansNode.height = 0; // null tree's height is -1 } else if (comp.compare(t, subTree.t) < 0) // insert to the leftSubTree of subTree { subTree.leftChild = insertTree(subTree.leftChild, t, v); if (getHeight(subTree.leftChild) - getHeight(subTree.rightChild) == 2) // subtree is the minimum unbalanced subTree { // singleLeftRotate or doubleLeftRightRorate if (getHeight(subTree.leftChild.leftChild) > getHeight(subTree.leftChild.rightChild)) { ansNode = singleLeftRotate(subTree); } else { ansNode = doubleLeftRightRotate(subTree); } } else { // Only the change of structure of tree causes the change of it's height subTree.height = 1 + (getHeight(subTree.leftChild) >= getHeight(subTree.rightChild) ? getHeight(subTree.leftChild) : getHeight(subTree.rightChild)); ansNode = subTree; } } else if (comp.compare(t, subTree.t) > 0) // insert to the rightSubTree of subTree { subTree.rightChild = insertTree(subTree.rightChild, t, v); if (getHeight(subTree.rightChild) - getHeight(subTree.leftChild) == 2) // subtree is the minimum unbalanced subTree { // singleLeftRotate or doubleLeftRightRorate if (getHeight(subTree.rightChild.rightChild) > getHeight(subTree.rightChild.leftChild)) { ansNode = singleRightRotate(subTree); } else { ansNode = doubleRightLeftRotate(subTree); } } else { // Only the change of structure of tree causes the change of it's height subTree.height = 1 + (getHeight(subTree.leftChild) > getHeight(subTree.rightChild) ? getHeight(subTree.leftChild) : getHeight(subTree.rightChild)); ansNode = subTree; } } return ansNode; }
/** * {@inheritDoc} * * @see java.util.NavigableSet#headSet(Object, boolean) * @since 1.6 */ @SuppressWarnings("unchecked") public NavigableSet<E> headSet(E end, boolean endInclusive) { // Check for errors Comparator<? super E> c = backingMap.comparator(); if (c == null) { ((net.sourceforge.retroweaver.harmony.runtime.java.lang.Comparable<E>) end).compareTo(end); } else { c.compare(end, end); } return new TreeSet<E>(backingMap.headMap(end, endInclusive)); }
/** * Like gallopLeft, except that if the range contains an element equal to key, gallopRight returns * the index after the rightmost equal element. * * @param key the key whose insertion point to search for * @param a the array in which to search * @param base the index of the first element in the range * @param len the length of the range; must be > 0 * @param hint the index at which to begin the search, 0 <= hint < n. The closer hint is to the * result, the faster this method will run. * @param c the comparator used to order the range, and to search * @return the int k, 0 <= k <= n such that a[b + k - 1] <= key < a[b + k] */ private static <T> int gallopRight( T key, T[] a, int base, int len, int hint, Comparator<? super T> c) { assert len > 0 && hint >= 0 && hint < len; int ofs = 1; int lastOfs = 0; if (c.compare(key, a[base + hint]) < 0) { // Gallop left until a[b+hint - ofs] <= key < a[b+hint - lastOfs] int maxOfs = hint + 1; while (ofs < maxOfs && c.compare(key, a[base + hint - ofs]) < 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to b int tmp = lastOfs; lastOfs = hint - ofs; ofs = hint - tmp; } else { // a[b + hint] <= key // Gallop right until a[b+hint + lastOfs] <= key < a[b+hint + ofs] int maxOfs = len - hint; while (ofs < maxOfs && c.compare(key, a[base + hint + ofs]) >= 0) { lastOfs = ofs; ofs = (ofs << 1) + 1; if (ofs <= 0) // int overflow ofs = maxOfs; } if (ofs > maxOfs) ofs = maxOfs; // Make offsets relative to b lastOfs += hint; ofs += hint; } assert -1 <= lastOfs && lastOfs < ofs && ofs <= len; /* * Now a[b + lastOfs] <= key < a[b + ofs], so key belongs somewhere to * the right of lastOfs but no farther right than ofs. Do a binary * search, with invariant a[b + lastOfs - 1] <= key < a[b + ofs]. */ lastOfs++; while (lastOfs < ofs) { int m = lastOfs + ((ofs - lastOfs) >>> 1); if (c.compare(key, a[base + m]) < 0) ofs = m; // key < a[b + m] else lastOfs = m + 1; // a[b + m] <= key } assert lastOfs == ofs; // so a[b + ofs - 1] <= key < a[b + ofs] return ofs; }
/** * {@inheritDoc} * * @see java.util.NavigableSet#tailSet(Object, boolean) * @since 1.6 */ @SuppressWarnings("unchecked") public NavigableSet<E> tailSet(E start, boolean startInclusive) { // Check for errors Comparator<? super E> c = backingMap.comparator(); if (c == null) { ((net.sourceforge.retroweaver.harmony.runtime.java.lang.Comparable<E>) start) .compareTo(start); } else { c.compare(start, start); } return new TreeSet<E>(backingMap.tailMap(start, startInclusive)); }
public void launch() { // this script attempts to use polymorphism to get the // maximum of 2 different numbers provided as a double, string or integer // the class assumes input of a double so that we don't get any loss of precision // the alternative was to use an integer and cast the double to an integer but wouldn't have // been able to compare non whole numbers in that case Comparator compare = new Comparator(); System.out.println("Max =" + compare.getMax(4.26, 4.33)); // compare doubles System.out.println("Max =" + compare.getMax(4, 3)); // compare integers System.out.println("Max =" + compare.getMax("4.89", "4.88")); // compare strings }
/** * {@inheritDoc} * * @see java.util.NavigableSet#subSet(Object, boolean, Object, boolean) * @since 1.6 */ @SuppressWarnings("unchecked") public NavigableSet<E> subSet(E start, boolean startInclusive, E end, boolean endInclusive) { Comparator<? super E> c = backingMap.comparator(); int compare = (c == null) ? ((net.sourceforge.retroweaver.harmony.runtime.java.lang.Comparable<E>) start) .compareTo(end) : c.compare(start, end); if (compare <= 0) { return new TreeSet<E>(backingMap.subMap(start, startInclusive, end, endInclusive)); } throw new IllegalArgumentException(); }
private boolean contains(BinaryTreeNodeImpl<E> node, BinaryTreeNodeImpl<E> subroot) { count++; if (subroot == null) { return false; } if (c.compare(node.getData(), subroot.getData()) == 0) { return true; } if (c.compare(node.getData(), subroot.getData()) < 0) { return contains(node, (BinaryTreeNodeImpl<E>) subroot.getLeft()); } else { return contains(node, (BinaryTreeNodeImpl<E>) subroot.getRight()); } }
/** * Adds all of the elements in the specified collection to this set. * * @param c collection containing elements to be added to this set * @return {@code true} if this set changed as a result of the call * @throws ClassCastException if the elements provided cannot be compared with the elements * currently in the set * @throws NullPointerException if the specified collection is null or if any element is null and * this set uses natural ordering, or its comparator does not permit null elements */ public boolean addAll(Collection<? extends E> c) { // Use linear-time version if applicable if (m.size() == 0 && c.size() > 0 && c instanceof SortedSet && m instanceof TreeMap) { SortedSet<? extends E> set = (SortedSet<? extends E>) c; TreeMap<E, Object> map = (TreeMap<E, Object>) m; Comparator<? super E> cc = (Comparator<? super E>) set.comparator(); Comparator<? super E> mc = map.comparator(); if (cc == mc || (cc != null && cc.equals(mc))) { map.addAllForTreeSet(set, PRESENT); return true; } } return super.addAll(c); }
@Test public void testReverseOrderRandomIntegers() { Comparator<Integer> naturalOrder = new NaturalOrder<Integer>(); Comparator<Integer> reverse = CollectionUtil.reverseOrder(naturalOrder); Random random = new Random(243249878l); // Stable "random" sequence for (int i = 0; i < 65536; i++) { // Verified to be ~ 50/50 lt/gt int integer = random.nextInt(); int integerToo = random.nextInt(); assertEquals(0, reverse.compare(integer, integer)); assertEquals(0, reverse.compare(integerToo, integerToo)); int natural = naturalOrder.compare(integer, integerToo); if (natural == 0) { // Actually never hits, but eq case is tested above assertEquals(0, reverse.compare(integer, integerToo)); } else if (natural < 0) { assertTrue(reverse.compare(integer, integerToo) > 0); } else { assertTrue(reverse.compare(integer, integerToo) < 0); } } }
@Override public void processPicture() { Comparator imageComparator = new Comparator(); imageComparator.setImages(primaryImage, currentImage); Log.d(LOG_TAG, imageComparator.difference + ""); if (!imageComparator.isSame()) { isOK = false; if (!warningSent) sendWarning(); } else { isOK = true; warningSent = false; } }
/** * Returns the length of the run beginning at the specified position in the specified array and * reverses the run if it is descending (ensuring that the run will always be ascending when the * method returns). * * <p>A run is the longest ascending sequence with: * * <p>a[lo] <= a[lo + 1] <= a[lo + 2] <= ... * * <p>or the longest descending sequence with: * * <p>a[lo] > a[lo + 1] > a[lo + 2] > ... * * <p>For its intended use in a stable mergesort, the strictness of the definition of "descending" * is needed so that the call can safely reverse a descending sequence without violating * stability. * * @param a the array in which a run is to be counted and possibly reversed * @param lo index of the first element in the run * @param hi index after the last element that may be contained in the run. It is required that * {@code lo < hi}. * @param c the comparator to used for the sort * @return the length of the run beginning at the specified position in the specified array */ private static <T> int countRunAndMakeAscending(T[] a, int lo, int hi, Comparator<? super T> c) { assert lo < hi; int runHi = lo + 1; if (runHi == hi) return 1; // Find end of run, and reverse range if descending if (c.compare(a[runHi++], a[lo]) < 0) { // Descending while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) < 0) runHi++; reverseRange(a, lo, runHi); } else { // Ascending while (runHi < hi && c.compare(a[runHi], a[runHi - 1]) >= 0) runHi++; } return runHi - lo; }
@SuppressWarnings("unchecked") @Override public Array<T> sorted(Comparator<? super T> comparator) { final Object[] arr = toArray(this); Arrays.sort(arr, (o1, o2) -> comparator.compare((T) o1, (T) o2)); return wrap(arr); }
@Test public void testGetMaxDouble() { double test1 = 1; double test2 = 2; double output = test.getMax(test1, test2); assertEquals(2.0, output, 1); }
@Test public void testGetMaxString() { String test1 = "1"; String test2 = "2"; String output = test.getMax(test1, test2); assertEquals("2", output); }
public final void ensureSortedIfEnabled() { if (ENSURE_SORTED_PRECONDITIONS_ENABLED) { for (int i = 1; i < array.size(); i++) { Preconditions.checkState(comparator.compare(array.get(i - 1), array.get(i)) <= 0); } } }
@Test public void testGetMaxInt() { int test1 = 1; int test2 = 2; int output = test.getMax(test1, test2); assertEquals(2, output); }
/** * Removes given value from the set and returns the instance stored in the set or {@code null} if * value was not found. * * @param val Value to remove. * @return The instance that was stored in the set or {@code null}. */ @Nullable public V removex(V val) { A.notNull(val, "val"); if (comp == null || !strict) { for (Iterator<V> it = vals.iterator(); it.hasNext(); ) { V v = it.next(); if (v.equals(val)) { it.remove(); return v; } } return null; } assert comp != null && strict; for (Iterator<V> it = vals.iterator(); it.hasNext(); ) { V v = it.next(); // Prefer equals to comparator. if (v.equals(val)) { it.remove(); return v; } if (comp.compare(v, val) > 0) break; } return null; }
public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); String[] temp = in.readLine().split(" "); int n = Integer.parseInt(temp[0]); int s = Integer.parseInt(temp[1]); HashMap<Integer, Integer> buy = new HashMap<>(); HashMap<Integer, Integer> sell = new HashMap<>(); for (int i = 1; i <= n; i++) { temp = in.readLine().split(" "); int p = Integer.parseInt(temp[1]); int q = Integer.parseInt(temp[2]); if (temp[0].charAt(0) == 'B') { if (buy.containsKey(p)) buy.put(p, buy.get(p) + q); else buy.put(p, q); } else { if (sell.containsKey(p)) sell.put(p, sell.get(p) + q); else sell.put(p, q); } } ArrayList<Integer> buyArr = new ArrayList<>(); ArrayList<Integer> sellArr = new ArrayList<>(); for (Integer i : buy.keySet()) buyArr.add(i); for (Integer i : sell.keySet()) sellArr.add(i); Collections.sort(buyArr, Comparator.reverseOrder()); Collections.sort(sellArr); for (int i = Math.min(s, sellArr.size()) - 1; i >= 0; i--) System.out.println("S " + sellArr.get(i) + " " + sell.get(sellArr.get(i))); for (int i = 0; i < s && i < buyArr.size(); i++) System.out.println("B " + buyArr.get(i) + " " + buy.get(buyArr.get(i))); }
/** * Set pairwise ordering between all factories according a comparator. Calls to <code> * {@linkplain Comparator#compare compare}(factory1, factory2)</code> should returns: * * <ul> * <li>{@code -1} if {@code factory1} is preferred to {@code factory2} * <li>{@code +1} if {@code factory2} is preferred to {@code factory1} * <li>{@code 0} if there is no preferred order between {@code factory1} and {@code factory2} * </ul> * * @param <T> The class represented by the {@code category} argument. * @param category The category to set ordering. * @param comparator The comparator to use for ordering. * @return {@code true} if at least one ordering setting has been modified as a consequence of * this call. */ public <T> boolean setOrdering(final Class<T> category, final Comparator<T> comparator) { boolean set = false; final List<T> previous = new ArrayList<T>(); for (final Iterator<T> it = getServiceProviders(category, false); it.hasNext(); ) { final T f1 = it.next(); for (int i = previous.size(); --i >= 0; ) { final T f2 = previous.get(i); final int c; try { c = comparator.compare(f1, f2); } catch (ClassCastException exception) { /* * This exception is expected if the user-supplied comparator follows strictly * the java.util.Comparator specification and has determined that it can't * compare the supplied factories. From ServiceRegistry point of view, it just * means that the ordering between those factories will stay undeterminated. */ continue; } if (c > 0) { set |= setOrdering(category, f1, f2); } else if (c < 0) { set |= setOrdering(category, f2, f1); } } previous.add(f1); } return set; }
/** * Finds the index of the best solution in the list according to a comparator * * @param solutionList * @param comparator * @return The index of the best solution */ public static <S extends Solution<?>> int findIndexOfBestSolution( List<S> solutionList, Comparator<S> comparator) { if (solutionList == null) { throw new JMetalException("The solution list is null"); } else if (solutionList.isEmpty()) { throw new JMetalException("The solution list is empty"); } else if (comparator == null) { throw new JMetalException("The comparator is null"); } int index = 0; S bestKnown = solutionList.get(0); S candidateSolution; int flag; for (int i = 1; i < solutionList.size(); i++) { candidateSolution = solutionList.get(i); flag = comparator.compare(bestKnown, candidateSolution); if (flag == 1) { index = i; bestKnown = candidateSolution; } } return index; }
public static void main(String[] args) { Scanner sc = new Scanner(System.in); String[] numbers = sc.nextLine().split(" "); String sort = sc.nextLine(); if (sort.equals("Ascending")) { List<Integer> output = Arrays.stream(numbers).map(Integer::parseInt).sorted().collect(Collectors.toList()); for (Object items : output) { System.out.print(items + " "); } } else if (sort.equals("Descending")) { List<Integer> output = Arrays.stream(numbers) .map(Integer::parseInt) .sorted(Comparator.reverseOrder()) .collect(Collectors.toList()); for (Object items : output) { System.out.print(items + " "); } } }
public static <S extends Solution<?>> boolean isSolutionDominatedBySolutionList( S solution, List<? extends S> solutionSet) { boolean result = false; Comparator<S> dominance = new DominanceComparator<S>(); int i = 0; while (!result && (i < solutionSet.size())) { if (dominance.compare(solution, solutionSet.get(i)) == 1) { result = true; } i++; } return result; }
public static void main(String[] args) { // Methods in Comparator List<Person> people = new ArrayList<>(); people.sort( Comparator.comparing(Person::getLastName) .thenComparing(Person::getFirstName) .thenComparing( Person::getEmailAddress, Comparator.nullsLast(String.CASE_INSENSITIVE_ORDER))); // Old way of initializing ThreadLocal: ThreadLocal<List<String>> oldThreadLocalString = new ThreadLocal<List<String>>() { @Override public List<String> initialValue() { return new ArrayList<>(); } }; System.out.println(oldThreadLocalString.get()); // New way: ThreadLocal<List<String>> newThreadLocalString = ThreadLocal.withInitial(ArrayList::new); System.out.println(newThreadLocalString.get()); // Java Optional Optional<Integer> optional = new ArrayList<Integer>().stream().min(Integer::compareTo); System.out.println(optional); // Files can now return streams try { Stream stream = Files.list(Paths.get("c:\\temp\\")); stream = Files.lines(Paths.get("c:\\temp\\"), Charset.forName("UTF_32")); stream = Files.find(Paths.get("c:\\"), 5, (T, U) -> (T == U)); } catch (IOException e) { UncheckedIOException ex = new UncheckedIOException("cause", e); System.out.println(ex.getMessage()); } // Rejoice, for we finally have string joins! String joinExample = String.join(",", "a", "b", "c", "4", "E", "6"); System.out.println(joinExample); StringJoiner joiner = new StringJoiner("-"); joiner.add("abbie"); joiner.add("doobie"); System.out.println(joiner.toString()); }
private V getValueTree(T t, Node<T, V> subTree) { V ansV = null; if (subTree == null) { // System.err.println("Key " + t + " does not exist."); // System.err.flush(); ansV = null; } else if (comp.compare(t, subTree.t) == 0) { ansV = subTree.v; } else if (comp.compare(t, subTree.t) < 0) { ansV = getValueTree(t, subTree.leftChild); } else if (comp.compare(t, subTree.t) > 0) { ansV = getValueTree(t, subTree.rightChild); } return ansV; }
@Override public <U> Array<T> sortBy( Comparator<? super U> comparator, Function<? super T, ? extends U> mapper) { final Function<? super T, ? extends U> domain = Function1.of(mapper::apply).memoized(); return toJavaStream() .sorted((e1, e2) -> comparator.compare(domain.apply(e1), domain.apply(e2))) .collect(collector()); }
@NotNull public static List<SymfonyInstallerVersion> getVersions(@NotNull String jsonContent) { JsonObject jsonObject = new JsonParser().parse(jsonContent).getAsJsonObject(); List<SymfonyInstallerVersion> symfonyInstallerVersions = new ArrayList<>(); // prevent adding duplicate version on alias names Set<String> aliasBranches = new HashSet<>(); // get alias version, in most common order for (String s : new String[] {"latest", "lts"}) { JsonElement asJsonObject = jsonObject.get(s); if (asJsonObject == null) { continue; } String asString = asJsonObject.getAsString(); aliasBranches.add(asString); symfonyInstallerVersions.add( new SymfonyInstallerVersion(s, String.format("%s (%s)", asString, s))); } List<SymfonyInstallerVersion> branches = new ArrayList<>(); Set<Map.Entry<String, JsonElement>> entries = jsonObject.entrySet(); for (Map.Entry<String, JsonElement> entry : entries) { if (!entry.getKey().matches("^\\d+\\.\\d+$")) { continue; } // "2.8.0-dev", "2.8.0-DEV" is not supported String asString = entry.getValue().getAsString(); if (asString.matches(".*[a-zA-Z].*") || aliasBranches.contains(asString)) { continue; } branches.add( new SymfonyInstallerVersion( asString, String.format("%s (%s)", entry.getKey(), asString))); } branches.sort(Comparator.comparing(SymfonyInstallerVersion::getVersion)); Collections.reverse(branches); symfonyInstallerVersions.addAll(branches); // we need reverse order for sorting them on version string List<SymfonyInstallerVersion> installableVersions = new ArrayList<>(); for (JsonElement installable : jsonObject.getAsJsonArray("installable")) { installableVersions.add(new SymfonyInstallerVersion(installable.getAsString())); } Collections.reverse(installableVersions); symfonyInstallerVersions.addAll(installableVersions); return symfonyInstallerVersions; }