List of usage examples for java.util Comparator compare
int compare(T o1, T o2);
From source file:Main.java
public static void main(String... args) { // Comparators Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("A", "Z"); Person p2 = new Person("B", "Z"); System.out.println(comparator.compare(p1, p2));// > 0 System.out.println(comparator.reversed().compare(p1, p2)); // < 0 }
From source file:Main.java
public static void main(String[] args) throws Exception { Comparator<Person> comparator = (p1, p2) -> p1.firstName.compareTo(p2.firstName); Person p1 = new Person("John", "Doe"); Person p2 = new Person("Alice", "Wonderland"); comparator.compare(p1, p2); // > 0 comparator.reversed().compare(p1, p2); // <0 }
From source file:org.jboss.dashboard.commons.comparator.ComparatorUtils.java
/** * Test compare methods.//ww w.j a v a2s .co m */ public static void main(String[] args) throws Exception { String[] stringArray = new String[] { "3", "4", "1" }; Long[] longArray = new Long[] { new Long(3), new Long(2), new Long(4) }; Boolean[] booleanArray = new Boolean[] { Boolean.FALSE, Boolean.TRUE, Boolean.FALSE }; List stringList = Arrays.asList(stringArray); List longList = Arrays.asList(longArray); List booleanList = Arrays.asList(booleanArray); List collection1 = Arrays.asList(new String[] { "A" }); List collection2 = Arrays.asList(new String[] { "B" }); Comparator comparator = new Comparator() { public int compare(Object o1, Object o2) { return ComparatorUtils.compare(o1, o2, -1); } }; Collections.sort(stringList, comparator); Collections.sort(longList, comparator); Collections.sort(booleanList, comparator); System.out.println(stringList); System.out.println(longList); System.out.println(booleanList); System.out.println(comparator.compare(collection1, collection2)); }
From source file:SortUtils.java
/** * Test method//from w w w . ja va2 s. c o m */ public static void main(String[] args) { Comparator cmp = new Comparator() { public int compare(Object o1, Object o2) { return ((Comparable) o1).compareTo(o2); } }; int n = 1000000; if (args.length == 1) try { n = Integer.parseInt(args[0]); } catch (Exception e) { System.err.println(e); } System.out.println("Generating " + n + " random integers..."); java.util.Random random = new java.util.Random(); Integer[] data = new Integer[n]; for (int i = 0; i < n; i++) { data[i] = new Integer(Math.abs(random.nextInt())); // data[i] = new Integer(i); } int[] indices; long time; System.out.print("Arrays.sort..."); time = System.currentTimeMillis(); Integer[] clone = (Integer[]) data.clone(); Arrays.sort(clone, cmp); System.out.println(System.currentTimeMillis() - time + "ms"); System.out.print("quicksort..."); indices = identity(n); time = System.currentTimeMillis(); sort(indices, data, cmp, false); System.out.println(System.currentTimeMillis() - time + "ms"); for (int i = 1; i < n; i++) if (cmp.compare(data[indices[i - 1]], data[indices[i]]) > 0) System.err.println("proplem: quickSort at " + i); System.out.print("quicksort stable..."); // indices = identity(n); time = System.currentTimeMillis(); sort(indices, data, cmp, true); System.out.println(System.currentTimeMillis() - time + "ms"); for (int i = 1; i < n; i++) { int res = cmp.compare(data[indices[i - 1]], data[indices[i]]); if (res > 0) System.err.println("proplem: quickSort stable at " + i); if (res == 0 && indices[i - 1] > indices[i]) System.err.println("proplem: quickSort stable (not stable) at " + i); } // System.out.print("cheapsort..."); // time = System.currentTimeMillis(); // indices = cheapSort(data, cmp); // System.out.println(System.currentTimeMillis()-time + "ms"); // for (int i = 1; i < n; i++) // if (cmp.compare(data[indices[i-1]], data[indices[i]]) > 0) // System.err.println("proplem: cheapSort at " + i); System.out.print("permutate copy..."); time = System.currentTimeMillis(); Object[] data_copy = permute(inverse(indices), data, true); System.out.println(System.currentTimeMillis() - time + "ms"); for (int i = 1; i < n; i++) if (cmp.compare(data_copy[i - 1], data_copy[i]) > 0) System.err.println("proplem: permute copy at " + i); System.out.print("permutate original..."); time = System.currentTimeMillis(); permute(inverse(indices), data, false); System.out.println(System.currentTimeMillis() - time + "ms"); for (int i = 1; i < n; i++) if (cmp.compare(data[i - 1], data[i]) > 0) System.err.println("proplem: permute original at " + i); }
From source file:csv.sorting.PrepareWeatherData.java
public static void main(String[] args) throws Exception { // Path to read the CSV data from: final Path csvStationDataFilePath = FileSystems.getDefault() .getPath("C:\\Users\\philipp\\Downloads\\csv\\201503station.txt"); final Path csvLocalWeatherDataUnsortedFilePath = FileSystems.getDefault() .getPath("C:\\Users\\philipp\\Downloads\\csv\\201503hourly.txt"); final Path csvLocalWeatherDataSortedFilePath = FileSystems.getDefault() .getPath("C:\\Users\\philipp\\Downloads\\csv\\201503hourly_sorted.txt"); // A map between the WBAN and Station for faster Lookups: final Map<String, Station> stationMap = getStationMap(csvStationDataFilePath); // Holds the List of Sorted DateTimes (including ZoneOffset): List<Integer> indices = new ArrayList<>(); // Comparator for sorting the File: Comparator<OffsetDateTime> byMeasurementTime = (e1, e2) -> e1.compareTo(e2); // Get the sorted indices from the stream of LocalWeatherData Elements: try (Stream<CsvMappingResult<csv.model.LocalWeatherData>> stream = getLocalWeatherData( csvLocalWeatherDataUnsortedFilePath)) { // Holds the current line index, when processing the input Stream: AtomicInteger currentIndex = new AtomicInteger(1); // We want to get a list of indices, which sorts the CSV file by measurement time: indices = stream//from w w w .j av a2s .c o m // Skip the CSV Header: .skip(1) // Start by enumerating ALL mapping results: .map(x -> new ImmutablePair<>(currentIndex.getAndAdd(1), x)) // Then only take those lines, that are actually valid: .filter(x -> x.getRight().isValid()) // Now take the parsed entity from the CsvMappingResult: .map(x -> new ImmutablePair<>(x.getLeft(), x.getRight().getResult())) // Take only those measurements, that are also available in the list of stations: .filter(x -> stationMap.containsKey(x.getRight().getWban())) // Get the OffsetDateTime from the LocalWeatherData, which includes the ZoneOffset of the Station: .map(x -> { // Get the matching station: csv.model.Station station = stationMap.get(x.getRight().getWban()); // Calculate the OffsetDateTime from the given measurement: OffsetDateTime measurementTime = OffsetDateTime.of(x.getRight().getDate(), x.getRight().getTime(), ZoneOffset.ofHours(0)); // Build the Immutable pair with the Index again: return new ImmutablePair<>(x.getLeft(), measurementTime); }) // Now sort the Measurements by their Timestamp: .sorted((x, y) -> byMeasurementTime.compare(x.getRight(), y.getRight())) // Take only the Index: .map(x -> x.getLeft()) // And turn it into a List: .collect(Collectors.toList()); } // Now sorts the File by Line Number: writeSortedFileByIndices(csvLocalWeatherDataUnsortedFilePath, indices, csvLocalWeatherDataSortedFilePath); }
From source file:Main.java
/** * Checks if the given object (or range upper bound) falls under another * upper bound.//ww w . j a va 2 s .c o m * * <p>Generally, this is used to test if an object is under the specified * upper bound (in which case, the parameter {@code oIncluded} will be true). * But we can also tell if the upper bound of one range (specified by the * parameters {@code o} and {@code oIncluded}) falls under the upper bound * of another range (specified by {@code to} and {@code toInclusive}). * * @param <T> the type of the element * @param o the object * @param oIncluded true if {@code o} needs to be included in the range * @param to the upper bound of the range * @param toInclusive true if {@code to} is included in the range, false * otherwise * @param comp the comparator used to compare {@code o} to {@code to} * (cannot be null) * @return true if the specified object is less than the bound and the * bound is exclusive, true if the object is less than or equal * to the bound and the bound is inclusive, and false otherwise */ public static <T> boolean isInRangeHigh(T o, boolean oIncluded, T to, boolean toInclusive, Comparator<? super T> comp) { if (to != null) { int c = comp.compare(o, to); if (c > 0 || (c == 0 && oIncluded && !toInclusive)) { return false; } } return true; }
From source file:Main.java
public static <T> int floor(ArrayList<T> list, T key, Comparator<? super T> c) { if (c.compare(list.get(0), key) > 0) { return -1; }//from www . ja va2 s . com if (c.compare(list.get(list.size() - 1), key) <= 0) { return list.size() - 1; } int start = 0, end = list.size() - 1, res; T mid; while (start < end - 1) { mid = list.get((start + end) / 2); res = c.compare(mid, key); // System.out.println("res = " + res); // System.out.println("mid = " + mid); if (res > 0) { end = (start + end) / 2; } else { start = (start + end) / 2; } // System.out.println("start = " + start); // System.out.println("end = "+ end); } res = c.compare(list.get(end), key); if (res > 0) { return start; } else { if (res == 0) { return end; } else { return -1; } } }
From source file:Main.java
/** * Uses given comparator to compare all list items to the given object to see * if there are some equal objects in the list. * * @return true if there is at least one equal object, false otherwise *///from w w w . j a v a 2s. c o m public static final boolean contains(List list, Object object, Comparator comparator) { for (int i = 0; i < list.size(); i++) { if (comparator.compare(list.get(i), object) == 0) { return true; } } return false; }
From source file:Main.java
/** * Swaps the indices "a" and "b" in the array "indices" if the corresponding * data values data[indices[a]] is greater than data[indices[b]]. * @param <ComparableType> Type of data to compare to. * @param a first index//from w ww. j a va2 s. co m * @param b second index * @param indices array of indices to index into "data", which is * modified by this method. * @param data ArrayList of values, unchanged. * @param comparator Comparator used to determine if two values * are greater than, less than, or equal to each other. * @return * True if swapped, false if left alone. */ private static <ComparableType> boolean swapIfAGreaterThanB(int a, int b, int[] indices, ArrayList<? extends ComparableType> data, Comparator<? super ComparableType> comparator) { final boolean doSwap = comparator.compare(data.get(indices[a]), data.get(indices[b])) > 0; if (doSwap) { swapArrayValues(a, b, indices); } return doSwap; }
From source file:org.fede.calculator.web.controller.InvestmentController.java
private static <T> T min(T left, T right, Comparator<T> comparator) { return comparator.compare(left, right) < 0 ? left : right; }