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

The following are Jave code examples for showing how to use reverseOrder() of the java.util.Collections class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: plugin-id-ldap   File: AbstractContainerLdaRepository.java   View Source Code Vote up 6 votes
@Override
public Page<T> findAll(final Set<T> groups, final String criteria, final Pageable pageable, final Map<String, Comparator<T>> customComparators) {
	// Create the set with the right comparator
	final List<Sort.Order> orders = IteratorUtils.toList(ObjectUtils.defaultIfNull(pageable.getSort(), new ArrayList<Sort.Order>()).iterator());
	orders.add(DEFAULT_ORDER);
	final Sort.Order order = orders.get(0);
	Comparator<T> comparator = customComparators.get(order.getProperty());
	if (order.getDirection() == Direction.DESC) {
		comparator = Collections.reverseOrder(comparator);
	}
	final Set<T> result = new TreeSet<>(comparator);

	// Filter the groups, filtering by the criteria
	addFilteredByPattern(groups, criteria, result);

	// Apply in-memory pagination
	return inMemoryPagination.newPage(result, pageable);
}
 
Example 2
Project: elasticsearch_my   File: BytesStreamsTests.java   View Source Code Vote up 6 votes
public void testWriteMapWithConsistentOrder() throws IOException {
    Map<String, String> map =
        randomMap(new TreeMap<>(), randomIntBetween(2, 20),
            () -> randomAsciiOfLength(5),
            () -> randomAsciiOfLength(5));

    Map<String, Object> reverseMap = new TreeMap<>(Collections.reverseOrder());
    reverseMap.putAll(map);

    List<String> mapKeys = map.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());
    List<String> reverseMapKeys = reverseMap.entrySet().stream().map(Map.Entry::getKey).collect(Collectors.toList());

    assertNotEquals(mapKeys, reverseMapKeys);

    try (BytesStreamOutput output = new BytesStreamOutput(); BytesStreamOutput reverseMapOutput = new BytesStreamOutput()) {
        output.writeMapWithConsistentOrder(map);
        reverseMapOutput.writeMapWithConsistentOrder(reverseMap);

        assertEquals(output.bytes(), reverseMapOutput.bytes());
    }
}
 
Example 3
Project: monarch   File: GfshParser.java   View Source Code Vote up 6 votes
private CommandTarget locateExactMatchingTarget(final String userInput)// exact matching
    throws IllegalArgumentException, IllegalAccessException, InvocationTargetException {
  CommandTarget commandTarget = null;

  Map<String, CommandTarget> commandTargetsMap = commandManager.getCommands();
  // Reverse sort the command names because we should start from longer names
  // E.g. Consider commands "A", "A B" & user input as "A B --opt1=val1"
  // In this case, "A B" is the most probable match & should be matched first
  // which can be achieved by reversing natural order of sorting.
  Set<String> commandNamesReverseSorted = new TreeSet<String>(Collections.reverseOrder());
  commandNamesReverseSorted.addAll(commandTargetsMap.keySet());

  // Now we need to locate the CommandTargets from the entries in the map
  for (final String commandName : commandNamesReverseSorted) {
    if (userInput.startsWith(commandName) && commandWordsMatch(userInput, commandName)) {
      // This means that the user has entered the command & name matches exactly
      commandTarget = commandTargetsMap.get(commandName);
      if (commandTarget != null) {
        String remainingBuffer = StringUtils.removeStart(userInput, commandName);
        commandTarget = commandTarget.duplicate(commandName, remainingBuffer);
        break;
      }
    }
  }
  return commandTarget;
}
 
Example 4
Project: jdk8u-jdk   File: EmptyNavigableSet.java   View Source Code Vote up 6 votes
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 5
Project: buildAPKsApps   File: AudioEventCollector.java   View Source Code Vote up 6 votes
/**
 * @param nextListener
 *            A chained listener to which all audio events are passed.
 */
public AudioEventCollector(AudioEventListener nextListener) {
    this.nextListener = nextListener;
    final Comparator<AudioBufferInfo> lastRecordedBufferLastComparator =
        new Comparator<AudioBufferInfo>() {
        @Override
        public int compare(AudioBufferInfo a, AudioBufferInfo b) {
            if (a.getAudioBufferId() < b.getAudioBufferId()) {
                return -1;
            }
            if (a.getAudioBufferId() > b.getAudioBufferId()) {
                return 1;
            }
            return 0;
        }
    };
    recordedBuffersLastRecordedLast = new TreeSet<AudioBufferInfo>(
            lastRecordedBufferLastComparator);
    recordedBuffersLastRecordedFirst = new TreeSet<AudioBufferInfo>(
            Collections.reverseOrder(lastRecordedBufferLastComparator));
    resetHistory();
}
 
Example 6
Project: coordination_oru   File: TrajectoryEnvelopeTrackerRK4.java   View Source Code Vote up 6 votes
private TreeMap<Double,Double> getSlowdownProfile() {
	TreeMap<Double,Double> ret = new TreeMap<Double, Double>(Collections.reverseOrder());
	State tempStateBW = new State(0.0, 0.0);
	ret.put(tempStateBW.getVelocity(), tempStateBW.getPosition());

	double time = 0.0;
	double deltaTime = 0.5*(this.trackingPeriodInMillis/this.temporalResolution);
	//Compute where to slow down (can do forward here for both states...)
	while (tempStateBW.getVelocity() < MAX_VELOCITY*1.1) {
		double dampeningBW = getCurvatureDampening(getRobotReport(tempStateBW).getPathIndex(), true);
		//Use slightly conservative max deceleration (which is positive acceleration since we simulate FW dynamics)
		integrateRK4(tempStateBW, time, deltaTime, false, MAX_VELOCITY*1.1, dampeningBW, MAX_ACCELERATION);
		time += deltaTime;
		ret.put(tempStateBW.getVelocity(), tempStateBW.getPosition());
	}
	
	//for (Double speed : ret.keySet()) System.out.println("@speed " + speed + " --> " + ret.get(speed));
	return ret;
}
 
Example 7
Project: DIA-Umpire-Maven   File: ProtID.java   View Source Code Vote up 6 votes
public float GetAbundanceByMS1_TopN(int topN, float pepweight) {
    if (PeptideID.isEmpty()) {
        return 0;
    }
    PriorityQueue<Float> TopQueue = new PriorityQueue<>(PeptideID.size(), Collections.reverseOrder());
    for (PepIonID peptide : PeptideID.values()) {
        if (peptide.PeakHeight != null && peptide.FilteringWeight > pepweight) {
            TopQueue.add(peptide.PeakHeight[0]);
        }
    }

    float totalabundance = 0f;
    int num = Math.min(topN, TopQueue.size());

    for (int i = 0; i < num; i++) {
        totalabundance += TopQueue.poll();
    }
    return totalabundance / num;
}
 
Example 8
Project: ChromeLikeTabSwitcher   File: TabletTabSwitcherLayout.java   View Source Code Vote up 6 votes
@Override
protected final void onInflateLayout(@NonNull final LayoutInflater inflater,
                                     final boolean tabsOnly) {
    if (!tabsOnly) {
        inflater.inflate(R.layout.tablet_layout, getTabSwitcher(), true);
    }

    primaryToolbar = getTabSwitcher().findViewById(R.id.primary_toolbar);
    secondaryToolbar = getTabSwitcher().findViewById(R.id.secondary_toolbar);
    tabContainer = getTabSwitcher().findViewById(R.id.tab_container);
    borderView = getTabSwitcher().findViewById(R.id.border_view);
    ViewGroup contentContainer = getTabSwitcher().findViewById(R.id.content_container);
    contentViewRecycler = new AttachedViewRecycler<>(contentContainer, inflater);
    tabRecyclerAdapter = new TabletTabRecyclerAdapter(getTabSwitcher(), getModel(), getStyle());
    getModel().addListener(tabRecyclerAdapter);
    tabViewRecycler = new AttachedViewRecycler<>(tabContainer, inflater,
            Collections.reverseOrder(new TabletItemComparator(getTabSwitcher())));
    tabViewRecycler.setAdapter(tabRecyclerAdapter);
    tabRecyclerAdapter.setViewRecycler(tabViewRecycler);
    dragHandler =
            new TabletDragTabsEventHandler(getTabSwitcher(), getArithmetics(), tabViewRecycler);
    adaptTabContainerAndToolbarMargins();
    adaptBorderColor();
}
 
Example 9
Project: hack   File: HeapsFindTheRunningMedian.java   View Source Code Vote up 5 votes
@SuppressWarnings("Duplicates")
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    PriorityQueue<Integer> minHeap = new PriorityQueue<>(10, Collections.reverseOrder());
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(10);

    int n = scanner.nextInt();

    for (int i = 0; i < n; i++) {
        int num = scanner.nextInt();

        if (minHeap.size() <= maxHeap.size()) {
            minHeap.add(num);
        } else {
            maxHeap.add(num);
        }

        while (!minHeap.isEmpty() && !maxHeap.isEmpty() && minHeap.peek() > maxHeap.peek()) {
            int min = minHeap.poll();
            int max = maxHeap.poll();

            minHeap.add(max);
            maxHeap.add(min);
        }

        double median = (minHeap.size() == maxHeap.size() ? ((minHeap.peek() + maxHeap.peek()) / 2.0) : minHeap.peek());

        System.out.println(median);
    }
}
 
Example 10
Project: data-structures-and-algorithm   File: TestPriorityQueue.java   View Source Code Vote up 5 votes
public void testPQOperation() {
    Integer[] data = {12, 5, 3, 6, 4, 2, 0, 23, -23, 982, 6028, 4039, 123, 9, 89, 2, 4, 9, 8, 54, 17, 90};
    PriorityQueue<Integer> pq = new PriorityQueue<Integer>(data);
    assertEquals(false, pq.isEmpty());
    assertEquals(data.length, pq.size());
    assertEquals(new Integer(-23), pq.peek());
    pq.add(-300);
    assertEquals(new Integer(-300), pq.poll());
    assertEquals(new Integer(-23), pq.poll());
    assertEquals(data.length-1, pq.size());
    
    pq.clear();
    assertEquals(true, pq.isEmpty());
    
    pq = new PriorityQueue<Integer>(data, Collections.reverseOrder());
    assertEquals(new Integer(6028), pq.peek());
    pq.add(30000);
    assertEquals(new Integer(30000), pq.poll());
    assertEquals(new Integer(6028), pq.poll());
    assertEquals(data.length-1, pq.size());
    
    pq = new PriorityQueue<Integer>(Collections.reverseOrder());
    
    for (int i=0; i<300; i++) {
        pq.add(234 + i);
    }
    assertEquals(300, pq.size());
    assertEquals(new Integer(234+299), pq.poll());
    
    for (int i=0; i<250; i++) {
        pq.poll();
    }
    assertEquals(49, pq.size());
    
}
 
Example 11
Project: apache-tomcat-7.0.73-with-comment   File: HTMLManagerServlet.java   View Source Code Vote up 5 votes
/**
 * 
 * @param cn Name of the application for which the sessions will be listed
 * @param req
 * @param resp
 * @param smClient  StringManager for the client's locale
 * @throws ServletException
 * @throws IOException
 */
protected void displaySessionsListPage(ContextName cn,
        HttpServletRequest req, HttpServletResponse resp,
        StringManager smClient)
        throws ServletException, IOException {
    List<Session> sessions = getSessionsForName(cn, smClient);
    String sortBy = req.getParameter("sort");
    String orderBy = null;
    if (null != sortBy && !"".equals(sortBy.trim())) {
        Comparator<Session> comparator = getComparator(sortBy);
        if (comparator != null) {
            orderBy = req.getParameter("order");
            if ("DESC".equalsIgnoreCase(orderBy)) {
                comparator = Collections.reverseOrder(comparator);
                orderBy = "ASC";
            } else {
                orderBy = "DESC";
            }
            try {
                Collections.sort(sessions, comparator);
            } catch (IllegalStateException ise) {
                // at least 1 of the sessions is invalidated
                req.setAttribute(APPLICATION_ERROR, "Can't sort session list: one session is invalidated");
            }
        } else {
            log("WARNING: unknown sort order: " + sortBy);
        }
    }
    // keep sort order
    req.setAttribute("sort", sortBy);
    req.setAttribute("order", orderBy);
    req.setAttribute("activeSessions", sessions);
    //strong>NOTE</strong> - This header will be overridden
    // automatically if a <code>RequestDispatcher.forward()</code> call is
    // ultimately invoked.
    resp.setHeader("Pragma", "No-cache"); // HTTP 1.0
    resp.setHeader("Cache-Control", "no-cache,no-store,max-age=0"); // HTTP 1.1
    resp.setDateHeader("Expires", 0); // 0 means now
    getServletContext().getRequestDispatcher(sessionsListJspPath).include(req, resp);
}
 
Example 12
Project: SciChart.Android.Examples   File: ExampleSearchProvider.java   View Source Code Vote up 5 votes
private Set<UUID> rankDocument(String[] terms, List<UUID> pageIds, Map<String, Posting> invertedIndex) {
    final double[] queryVector = new double[terms.length];
    final Map<UUID, double[]> docVectors = new HashMap<>();
    final Map<UUID, Double> docScores = new TreeMap<>(Collections.reverseOrder());
    for (int i = 0; i < terms.length; i++) {
        final String term = terms[i];
        if (!invertedIndex.containsKey(term)) {
            continue;
        }
        final Posting posting = invertedIndex.get(term);
        queryVector[i] = posting.invertedDocumentFrequency;

        for (TermInfo termInfo : posting.termInfos) {
            final UUID examplePageId = termInfo.examplePageId;
            if (pageIds.contains(examplePageId)) {
                if (!docVectors.containsKey(examplePageId)) {
                    docVectors.put(examplePageId, new double[terms.length]);
                }
                docVectors.get(examplePageId)[i] = termInfo.termFrequency;
            }
        }
    }

    for (Map.Entry<UUID, double[]> entry : docVectors.entrySet()) {
        final double dotProduct = dotProduct(entry.getValue(), queryVector);
        docScores.put(entry.getKey(), dotProduct);
    }

    return sortByComparator(docScores).keySet();
}
 
Example 13
Project: AHANLP   File: TextRankSentence.java   View Source Code Vote up 5 votes
private TextRankSentence(String document) {
    sentenceList = Segment.splitSentence(document, "[,,。::“”??!!;;]");
    senWordList = Segment.splitWordInSentences(sentenceList, true);
    senNum = sentenceList.size();
    weight = new float[senNum][senNum];
    weight_sum = new float[senNum];
    SenRank = new float[senNum];
    top = new TreeMap<Float, Integer>(Collections.reverseOrder());
    initParam();
    calSenRanks();
    for (int i = 0; i < senNum; ++i) // 按rank值排序
        top.put(SenRank[i], i);
}
 
Example 14
Project: javaide   File: SortArrayListInDescendingOrderExample.java   View Source Code Vote up 5 votes
public static void main(String[] args) {

    //create an ArrayList object
    ArrayList arrayList = new ArrayList();

    //Add elements to Arraylist
    arrayList.add("A");
    arrayList.add("B");
    arrayList.add("C");
    arrayList.add("D");
    arrayList.add("E");

    /*
      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 ArrayList in descending order : " + arrayList);

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

    Collections.sort(arrayList, comparator);
    System.out.println("After sorting ArrayList in descending order : " + arrayList);
  }
 
Example 15
Project: openjdk-jdk10   File: ConcurrentSkipListMap.java   View Source Code Vote up 5 votes
public Comparator<? super K> comparator() {
    Comparator<? super K> cmp = m.comparator();
    if (isDescending)
        return Collections.reverseOrder(cmp);
    else
        return cmp;
}
 
Example 16
Project: mmm   File: MutualInformationAnalyzer.java   View Source Code Vote up 5 votes
public MutualInformationAnalyzer(ItemsetMiner<LabelType> itemsetMiner, Class<? extends DistributionMetric> distributionMetricType, double minimalMutualInformation, boolean visualize) {
    super(itemsetMiner);
    this.distributionMetricType = distributionMetricType;
    this.minimalMutualInformation = minimalMutualInformation;
    this.visualize = visualize;
    logger.info("calculating mutual information for distribution metric {}", distributionMetricType);

    mutualInformation = new TreeMap<>(Collections.reverseOrder());
    calculateMutualInformation();
    createGraph();
}
 
Example 17
Project: passatuto   File: SimilarityMatrix.java   View Source Code Vote up 4 votes
public double[] writeROCCurveOfTopRank(File outputFile, double step, String add) throws Exception{
	double AUC=0;
	double F=0;
	int countF=0;
	TreeMap<Double, List<MatchType>> topScoringMatches=new TreeMap<Double,List<MatchType>>(Collections.reverseOrder());
	int[][] sortedIndizes=getIndizesOfSortedScores();
	int allPositives=0;
	int allNegatives=0;

	for(int i=0;i<sortedIndizes.length;i++){
		int ind=sortedIndizes[i][0];
		double value=getSimilarityValue(i,ind);
		if(Double.isNaN(value))continue;
		if(!topScoringMatches.containsKey(value))topScoringMatches.put(value, new ArrayList<MatchType>());			
		if(massbankQuery.get(i).hasEqualInChiKey(massbankDB.get(ind))){
			topScoringMatches.get(value).add(MatchType.TruePositiveMatch);
			allPositives++;
		}else{
			topScoringMatches.get(value).add(MatchType.FalsePositiveMatch);
			allNegatives++;
		}
	}

	List<double[]> values=new ArrayList<double[]>();
	XYSeriesCollection dataset = new XYSeriesCollection();
	XYSeries series=new XYSeries("ROCCurve " + getMethodsQueryAndDBString());
	double currentNumberTruePositives=0;
	double currentNumberFalsePositives=0;
	for(Entry<Double, List<MatchType>> matches:topScoringMatches.entrySet()){
		for(MatchType m:matches.getValue()){
			if(m.equals(MatchType.TruePositiveMatch))currentNumberTruePositives++;
			if(m.equals(MatchType.FalsePositiveMatch))currentNumberFalsePositives++;
		}

		double sensitivity=1.0*currentNumberTruePositives/allPositives;
		double EinsMinusSpecificity=1.0*currentNumberFalsePositives/allNegatives;
		values.add(new double[]{EinsMinusSpecificity,sensitivity});
		series.add(EinsMinusSpecificity,sensitivity);
		double precision=1.0*currentNumberTruePositives/(currentNumberTruePositives+currentNumberFalsePositives);
		F+=matches.getValue().size()*2*precision*sensitivity/(precision+sensitivity);
		countF+=matches.getValue().size();
	}
	dataset.addSeries(series);
	F/=countF;

	double lastX=0;		
	for(int i=1;i<values.size();i++){
		if(values.get(i-1)[0]!=values.get(i)[0]){
			AUC+=values.get(i-1)[1]*(values.get(i)[0]-lastX);
			lastX=values.get(i)[0];
		}
	}

	final JFreeChart chart = ChartFactory.createScatterPlot("ROCCurve","False Positive Rate", "True Positive Rate", dataset);
	ChartUtilities.saveChartAsJPEG(new File(outputFile.getAbsolutePath()+sep+add+"ROCCurveOfTopRank_"+getMethodsQueryAndDBString()+".jpg"), chart, 1000, 1000);

	return new double[]{AUC,F};
}
 
Example 18
Project: fresco_floodlight   File: NaiveSwitchDriverRegistry.java   View Source Code Vote up 4 votes
public NaiveSwitchDriverRegistry(@Nonnull IOFSwitchManager switchManager) {
    Preconditions.checkNotNull(switchManager, "switchManager must not be null");
    this.switchManager  = switchManager;
    switchBindingMap = new HashMap<String, IOFSwitchDriver>();
    switchDescSorted = new TreeSet<String>(Collections.reverseOrder());
}
 
Example 19
Project: iTAP-controller   File: NaiveSwitchDriverRegistry.java   View Source Code Vote up 4 votes
public NaiveSwitchDriverRegistry(@Nonnull IOFSwitchManager switchManager) {
    Preconditions.checkNotNull(switchManager, "switchManager must not be null");
    this.switchManager  = switchManager;
    switchBindingMap = new HashMap<String, IOFSwitchDriver>();
    switchDescSorted = new TreeSet<String>(Collections.reverseOrder());
}
 
Example 20
Project: guava-mock   File: ImmutableSortedSet.java   View Source Code Vote up 2 votes
/**
 * Returns a builder that creates immutable sorted sets whose elements are
 * ordered by the reverse of their natural ordering.
 */
public static <E extends Comparable<?>> Builder<E> reverseOrder() {
  return new Builder<E>(Collections.reverseOrder());
}