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

The following examples show how to use java.util.Collections#reverseOrder() . 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
Source File: EncoderTrainer.java    From ignite with 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 2
Source File: EmptyNavigableMap.java    From openjdk-8 with GNU General Public License v2.0 6 votes vote down vote up
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 3
Source File: EmptyNavigableSet.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
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 4
Source File: DegreeCurricularPlanManagementBackingBean.java    From fenixedu-academic with GNU Lesser General Public License v3.0 6 votes vote down vote up
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 5
Source File: EmptyNavigableSet.java    From jdk8u_jdk with GNU General Public License v2.0 6 votes vote down vote up
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
Source File: EmptyNavigableMap.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
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 7
Source File: SortVectorInDescendingOrderExample.java    From java-n-IDE-for-Android with Apache License 2.0 5 votes vote down vote up
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 8
Source File: SingularSpectrumTransform.java    From incubator-hivemall with Apache License 2.0 5 votes vote down vote up
/**
 * 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 9
Source File: Student.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 10
Source File: DisplayMessages.java    From erflute with 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 11
Source File: ConcurrentSkipListMap.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public Comparator<? super K> comparator() {
    Comparator<? super K> cmp = m.comparator();
    if (isDescending)
        return Collections.reverseOrder(cmp);
    else
        return cmp;
}
 
Example 12
Source File: FileSynchronizer.java    From Hive2Hive with 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 13
Source File: PhdIndividualProgramProcess.java    From fenixedu-academic with GNU Lesser General Public License v3.0 5 votes vote down vote up
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 14
Source File: SyncHelper.java    From PADListener with GNU General Public License v2.0 5 votes vote down vote up
@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 15
Source File: ConcurrentSkipListMap.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
public Comparator<? super K> comparator() {
    Comparator<? super K> cmp = m.comparator();
    if (isDescending)
        return Collections.reverseOrder(cmp);
    else
        return cmp;
}
 
Example 16
Source File: listSort.java    From openbd-core with GNU General Public License v3.0 5 votes vote down vote up
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 17
Source File: LibMatrixCountDistinct.java    From systemds with 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 18
Source File: SizeComparator.java    From commons-ip-math with 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 19
Source File: HeapHistogram.java    From javamelody with 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);
}
 
Example 20
Source File: StartAndSizeComparator.java    From commons-ip-math with 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);
}