Java Code Examples for java.util.Collections#reverseOrder()

The following examples show how to use java.util.Collections#reverseOrder() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
public static final boolean isDescending(SortedMap<?,?> set) {
    if (null == set.comparator()) {
        // natural order
        return false;
    }

    if (Collections.reverseOrder() == set.comparator()) {
        // reverse natural order.
        return true;
    }

    if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
        // it's a Collections.reverseOrder(Comparator).
        return true;
    }

    throw new IllegalStateException("can't determine ordering for " + set);
}
 
Example 2
Source Project: ignite   File: EncoderTrainer.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Transforms frequencies to the encoding values.
 *
 * @param frequencies Frequencies of categories for the specific feature.
 * @return Encoding values.
 */
private Map<String, Integer> transformFrequenciesToEncodingValues(Map<String, Integer> frequencies) {
    Comparator<Map.Entry<String, Integer>> comp;

    comp = encoderSortingStgy == EncoderSortingStrategy.FREQUENCY_DESC ? Map.Entry.comparingByValue() : Collections.reverseOrder(Map.Entry.comparingByValue());

    final HashMap<String, Integer> resMap = frequencies.entrySet()
        .stream()
        .sorted(comp)
        .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
            (oldValue, newValue) -> oldValue, LinkedHashMap::new));

    int amountOfLabels = frequencies.size();

    for (Map.Entry<String, Integer> m : resMap.entrySet())
        m.setValue(--amountOfLabels);

    return resMap;
}
 
Example 3
private List<SelectItem> readDurationTypes() {
    final List<SelectItem> result = new ArrayList<SelectItem>();
    final Set<AcademicPeriod> sortedPeriods = new TreeSet<>(Collections.reverseOrder());
    sortedPeriods.addAll(AcademicPeriod.values());

    for (final AcademicPeriod entry : sortedPeriods) {

        if (!(entry instanceof AcademicYears)) {
            //only year multiples are supported
            continue;
        }

        result.add(new SelectItem(entry.getRepresentationInStringFormat(), BundleUtil.getString(Bundle.ENUMERATION,
                entry.getName())));
    }

    result.add(0, new SelectItem(NO_SELECTION, BundleUtil.getString(Bundle.SCIENTIFIC, "choose")));

    return result;
}
 
Example 4
public static final boolean isDescending(SortedMap<?,?> set) {
    if (null == set.comparator()) {
        // natural order
        return false;
    }

    if (Collections.reverseOrder() == set.comparator()) {
        // reverse natural order.
        return true;
    }

    if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
        // it's a Collections.reverseOrder(Comparator).
        return true;
    }

    throw new IllegalStateException("can't determine ordering for " + set);
}
 
Example 5
public static final boolean isDescending(SortedSet<?> set) {
    if (null == set.comparator()) {
        // natural order
        return false;
    }

    if (Collections.reverseOrder() == set.comparator()) {
        // reverse natural order.
        return true;
    }

    if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
        // it's a Collections.reverseOrder(Comparator).
        return true;
    }

    throw new IllegalStateException("can't determine ordering for " + set);
}
 
Example 6
public static final boolean isDescending(SortedSet<?> set) {
    if (null == set.comparator()) {
        // natural order
        return false;
    }

    if (Collections.reverseOrder() == set.comparator()) {
        // reverse natural order.
        return true;
    }

    if (set.comparator().equals(Collections.reverseOrder(Collections.reverseOrder(set.comparator())))) {
        // it's a Collections.reverseOrder(Comparator).
        return true;
    }

    throw new IllegalStateException("can't determine ordering for " + set);
}
 
Example 7
public String sortList(String _listdata, String _type, String _order, String _delimiter) throws dataNotSupportedException {

		// create list from string
		List listElements = getListElements(_listdata, _type, _delimiter);

		// create a suitable comparator
		Comparator chosenComparator = null;
		if (_type.equals("TEXTNOCASE")) {
			chosenComparator = new caseInsensitiveStringComparator(_order.equals("ASC"));
		} else if (_type.equals("NUMERIC")) {
			chosenComparator = new numericComparator(_order.equals("ASC"));
		} else if (_order.equals("DESC")) {
			// if desc && text || numeric
			chosenComparator = Collections.reverseOrder();
		}

		// do the sort
		if (chosenComparator != null) {
			Collections.sort(listElements, chosenComparator);
		} else {
			// allow it to sort naturally. If the list elements are Doubles then the
			// list
			// will sort NUMERIC, ASC; TEXT, ASC if the elements are Strings.
			Collections.sort(listElements);
		}

		Iterator iter = listElements.iterator();
		String result = "";

		while (iter.hasNext()) {
			result += iter.next().toString() + _delimiter;
		}

		result = result.substring(0, result.lastIndexOf(_delimiter));
		return result;
	}
 
Example 8
public Comparator<? super K> comparator() {
    Comparator<? super K> cmp = m.comparator();
    if (isDescending)
        return Collections.reverseOrder(cmp);
    else
        return cmp;
}
 
Example 9
@SuppressLint("UseSparseArrays")
private Map<Integer, List<UserInfoMonsterModel>> reorgPadherderMonster(List<UserInfoMonsterModel> monsters) {
	MyLog.entry();

	final Map<Integer, List<UserInfoMonsterModel>> padherderMonstersById = new HashMap<Integer, List<UserInfoMonsterModel>>();

	for (final UserInfoMonsterModel monster : monsters) {
		final int padherderId = monster.getIdJp();
		try {
			// Get monster info to check if the captureId exists
			monsterInfoHelper.getMonsterInfo(padherderId);
			if (!padherderMonstersById.containsKey(padherderId)) {
				padherderMonstersById.put(padherderId, new ArrayList<UserInfoMonsterModel>());
			}
			padherderMonstersById.get(padherderId).add(monster);
		} catch (UnknownMonsterException e) {
			MyLog.warn("missing monster info for padherderId = " + e.getMonsterId());
			hasEncounteredUnknownMonster = true;
		}
	}

	// Sort monsters DESC
	final Comparator<MonsterModel> comparatorDesc = Collections.reverseOrder(new MonsterComparator(monsterInfoHelper));
	for (final List<UserInfoMonsterModel> capturedMonstersList : padherderMonstersById.values()) {
		Collections.sort(capturedMonstersList, comparatorDesc);
	}

	MyLog.exit();
	return padherderMonstersById;
}
 
Example 10
public PrecedentDegreeInformation getLatestPrecedentDegreeInformation() {
    TreeSet<PrecedentDegreeInformation> degreeInformations = new TreeSet<PrecedentDegreeInformation>(
            Collections.reverseOrder(PrecedentDegreeInformation.COMPARATOR_BY_EXECUTION_YEAR));
    ExecutionYear currentExecutionYear = ExecutionYear.readCurrentExecutionYear();
    for (PrecedentDegreeInformation pdi : getPrecedentDegreeInformationsSet()) {
        if (!pdi.getExecutionYear().isAfter(currentExecutionYear)) {
            degreeInformations.add(pdi);
        }
    }
    degreeInformations.addAll(getPrecedentDegreeInformationsSet());

    return (degreeInformations.iterator().hasNext()) ? degreeInformations.iterator().next() : null;
}
 
Example 11
Source Project: Hive2Hive   File: FileSynchronizer.java    License: MIT License 5 votes vote down vote up
/**
 * Returns a list of files that have been deleted from the disc during this client was offline
 * 
 * @return a list of files that has been deleted locally
 */
public List<Index> getDeletedLocally() {
	List<Index> deletedLocally = new ArrayList<Index>();

	for (String path : before.keySet()) {
		if (now.containsKey(path)) {
			// skip, this file is still here
			continue;
		} else {
			// test whether it is in the user profile
			Index node = userProfile.getFileByPath(new File(root, path), root);
			if (node != null) {
				// file is still in user profile
				if (node.isFolder()) {
					deletedLocally.add(node);
				} else {
					// check the hash value to not delete a modified file
					FileIndex fileNode = (FileIndex) node;
					if (HashUtil.compare(fileNode.getHash(), before.get(path))) {
						// file has not been modified remotely, delete it
						logger.debug("File '{}' has been deleted locally during absence.", path);
						deletedLocally.add(node);
					}
				}
			}
		}
	}

	// delete from behind
	sortNodesPreorder(deletedLocally);
	Collections.reverseOrder();

	logger.info("Found {} files/folders that have been deleted locally during absence.", deletedLocally.size());
	return deletedLocally;
}
 
Example 12
public Comparator<? super K> comparator() {
    Comparator<? super K> cmp = m.comparator();
    if (isDescending)
        return Collections.reverseOrder(cmp);
    else
        return cmp;
}
 
Example 13
Source Project: erflute   File: DisplayMessages.java    License: Apache License 2.0 5 votes vote down vote up
public static Map<String, String> getMessageMap(String prefix) {
    final Map<String, String> props = new TreeMap<>(Collections.reverseOrder());
    final Enumeration<String> keys = resource.getKeys();
    while (keys.hasMoreElements()) {
        final String key = keys.nextElement();
        if (key.startsWith(prefix)) {
            props.put(key, resource.getString(key));
        }
    }
    return props;
}
 
Example 14
public PersonalIngressionData getLatestPersonalIngressionData() {
    final ExecutionYear currentExecutionYear = ExecutionYear.readCurrentExecutionYear();
    final Comparator<PersonalIngressionData> comparator = Collections.reverseOrder(PersonalIngressionData.COMPARATOR_BY_EXECUTION_YEAR);
    return getPersonalIngressionsDataSet().stream()
        .filter(pid -> !pid.getExecutionYear().isAfter(currentExecutionYear))
        .sorted(comparator)
        .findFirst().orElse(null);
}
 
Example 15
/**
 * Implicit Krylov Approximation (IKA) based naive scoring.
 *
 * Number of iterations for the Power method and QR method is fixed to 1 for efficiency. This
 * may cause failure (i.e. meaningless scores) depending on datasets and initial values.
 *
 */
private double computeScoreIKA(@Nonnull final RealMatrix H, @Nonnull final RealMatrix G) {
    // assuming n = m = window, and keep track the left singular vector as `q`
    MatrixUtils.power1(G, q, 1, q, new double[window]);

    RealMatrix T = new Array2DRowRealMatrix(k, k);
    MatrixUtils.lanczosTridiagonalization(H.multiply(H.transpose()), q, T);

    double[] eigvals = new double[k];
    RealMatrix eigvecs = new Array2DRowRealMatrix(k, k);
    MatrixUtils.tridiagonalEigen(T, 1, eigvals, eigvecs);

    // tridiagonalEigen() returns unordered eigenvalues,
    // so the top-r eigenvectors should be picked carefully
    TreeMap<Double, Integer> map = new TreeMap<Double, Integer>(Collections.reverseOrder());
    for (int i = 0; i < k; i++) {
        map.put(eigvals[i], i);
    }
    Iterator<Integer> indices = map.values().iterator();

    double s = 0.d;
    for (int i = 0; i < r; i++) {
        if (!indices.hasNext()) {
            throw new IllegalStateException("Should not happen");
        }
        double v = eigvecs.getEntry(0, indices.next().intValue());
        s += v * v;
    }
    return 1.d - Math.sqrt(s);
}
 
Example 16
public static void main(String[] args) {

    //create a Vector object
    Vector v = new Vector();

    //Add elements to Vector
    v.add("1");
    v.add("2");
    v.add("3");
    v.add("4");
    v.add("5");

    /*
      To get comparator that imposes reverse order on a Collection use
      static Comparator reverseOrder() method of Collections class
    */

    Comparator comparator = Collections.reverseOrder();

    System.out.println("Before sorting Vector in descending order : " + v);

    /*
      To sort an Vector using comparator use,
      static void sort(List list, Comparator c) method of Collections class.
    */

    Collections.sort(v, comparator);
    System.out.println("After sorting Vector in descending order : " + v);
  }
 
Example 17
Source Project: commons-ip-math   File: StartAndSizeComparator.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <C extends Rangeable<C, R>, R extends Range<C, R>> Comparator<R> reverse() {
    return (Comparator<R>) (reverse == null ? reverse = Collections.reverseOrder(StartAndSizeComparator.<C, R>get()) : reverse);
}
 
Example 18
Source Project: systemds   File: LibMatrixCountDistinct.java    License: Apache License 2.0 4 votes vote down vote up
public SmallestPriorityQueue(int k) {
	smallestHashes = new PriorityQueue<>(k, Collections.reverseOrder());
	containedSet = new HashSet<>(1);
	this.k = k;
}
 
Example 19
Source Project: commons-ip-math   File: SizeComparator.java    License: MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
public static <R extends Range<?, R>> Comparator<R> reverse() {
    return (Comparator<R>) (reverse == null ? reverse = Collections.reverseOrder(SizeComparator.<R>get()) : reverse);
}
 
Example 20
Source Project: javamelody   File: HeapHistogram.java    License: Apache License 2.0 4 votes vote down vote up
private void sort() {
	final Comparator<ClassInfo> classInfoReversedComparator = Collections
			.reverseOrder(new ClassInfoComparator());
	Collections.sort(permGenClasses, classInfoReversedComparator);
	Collections.sort(classes, classInfoReversedComparator);
}