Example usage for java.util Comparator compare

List of usage examples for java.util Comparator compare

Introduction

In this page you can find the example usage for java.util Comparator compare.

Prototype

int compare(T o1, T o2);

Source Link

Document

Compares its two arguments for order.

Usage

From source file:org.openfaces.component.table.TableDataModel.java

private void sortRows(List<RowInfo> extractedRows) {
    if (table == null)
        return;//from   w w  w.  j  a  v a2 s.  c om
    final Comparator<Object> rowDataComparator = table.createRowDataComparator(sortingRules);
    Comparator<RowInfo> rowInfoComparator = new Comparator<RowInfo>() {
        public int compare(RowInfo rowInfo1, RowInfo rowInfo2) {
            return rowDataComparator.compare(rowInfo1.getRowData(), rowInfo2.getRowData());
        }
    };
    if (rowDataComparator != null)
        Collections.sort(extractedRows, rowInfoComparator);
}

From source file:org.briljantframework.data.vector.AbstractVector.java

@Override
public <T> Vector sort(Class<T> cls, Comparator<T> cmp) {
    Index.Builder index = getIndex().newCopyBuilder();
    VectorLocationGetter loc = loc();//from w  w w. j a  v  a2  s.  c  om
    index.sortIterationOrder((a, b) -> cmp.compare(loc.get(cls, a), loc.get(cls, b)));
    return shallowCopy(index.build());
}

From source file:org.springframework.web.servlet.handler.AbstractHandlerMethodMapping.java

/**
 * Look up the best-matching handler method for the current request.
 * If multiple matches are found, the best match is selected.
 * @param lookupPath mapping lookup path within the current servlet mapping
 * @param request the current request//from w w w.j  av a2s  . co m
 * @return the best-matching handler method, or {@code null} if no match
 * @see #handleMatch(Object, String, HttpServletRequest)
 * @see #handleNoMatch(Set, String, HttpServletRequest)
 */
@Nullable
protected HandlerMethod lookupHandlerMethod(String lookupPath, HttpServletRequest request) throws Exception {
    List<Match> matches = new ArrayList<>();
    List<T> directPathMatches = this.mappingRegistry.getMappingsByUrl(lookupPath);
    if (directPathMatches != null) {
        addMatchingMappings(directPathMatches, matches, request);
    }
    if (matches.isEmpty()) {
        // No choice but to go through all mappings...
        addMatchingMappings(this.mappingRegistry.getMappings().keySet(), matches, request);
    }

    if (!matches.isEmpty()) {
        Comparator<Match> comparator = new MatchComparator(getMappingComparator(request));
        matches.sort(comparator);
        Match bestMatch = matches.get(0);
        if (matches.size() > 1) {
            if (logger.isTraceEnabled()) {
                logger.trace(matches.size() + " matching mapppings: " + matches);
            }
            if (CorsUtils.isPreFlightRequest(request)) {
                return PREFLIGHT_AMBIGUOUS_MATCH;
            }
            Match secondBestMatch = matches.get(1);
            if (comparator.compare(bestMatch, secondBestMatch) == 0) {
                Method m1 = bestMatch.handlerMethod.getMethod();
                Method m2 = secondBestMatch.handlerMethod.getMethod();
                String uri = request.getRequestURI();
                throw new IllegalStateException(
                        "Ambiguous handler methods mapped for '" + uri + "': {" + m1 + ", " + m2 + "}");
            }
        }
        handleMatch(bestMatch.mapping, lookupPath, request);
        return bestMatch.handlerMethod;
    } else {
        return handleNoMatch(this.mappingRegistry.getMappings().keySet(), lookupPath, request);
    }
}

From source file:org.kuali.ole.gl.batch.BatchSortUtil.java

private static void mergeFiles(File tempSortDir, int numFiles, String outputFileName,
        Comparator<String> comparator) {
    try {//from  w w w.  j av a2s.  co  m
        ArrayList<FileReader> mergefr = new ArrayList<FileReader>(numFiles);
        ArrayList<BufferedReader> mergefbr = new ArrayList<BufferedReader>(numFiles);
        // temp buffer for writing - contains the minimum record from each file
        ArrayList<String> fileRows = new ArrayList<String>(numFiles);

        BufferedWriter bw = new BufferedWriter(new FileWriter(outputFileName));

        boolean someFileStillHasRows = false;

        // Iterate over all the files, getting the first line in each file
        for (int i = 0; i < numFiles; i++) {
            // open a file reader for each file
            mergefr.add(new FileReader(new File(tempSortDir, "chunk_" + i)));
            mergefbr.add(new BufferedReader(mergefr.get(i)));

            // get the first row
            String line = mergefbr.get(i).readLine();
            if (line != null) {
                fileRows.add(line);
                someFileStillHasRows = true;
            } else {
                fileRows.add(null);
            }
        }

        while (someFileStillHasRows) {
            String min = null;
            int minIndex = 0; // index of the file with the minimum record

            // init for later compare - assume the first file has the minimum
            String line = fileRows.get(0);
            if (line != null) {
                min = line;
                minIndex = 0;
            } else {
                min = null;
                minIndex = -1;
            }

            // determine the minimum record of the top lines of each file
            // check which one is min
            for (int i = 1; i < fileRows.size(); i++) {
                line = fileRows.get(i);
                if (line != null) {
                    if (min != null) {
                        if (comparator.compare(line, min) < 0) {
                            minIndex = i;
                            min = line;
                        }
                    } else {
                        min = line;
                        minIndex = i;
                    }
                }
            }

            if (minIndex < 0) {
                someFileStillHasRows = false;
            } else {
                // write to the sorted file
                bw.append(fileRows.get(minIndex)).append('\n');

                // get another row from the file that had the min
                line = mergefbr.get(minIndex).readLine();
                if (line != null) {
                    fileRows.set(minIndex, line);
                } else { // file is out of rows, set to null so it is ignored
                    fileRows.set(minIndex, null);
                }
            }
            // check if one still has rows
            for (int i = 0; i < fileRows.size(); i++) {
                someFileStillHasRows = false;
                if (fileRows.get(i) != null) {
                    if (minIndex < 0) {
                        throw new RuntimeException(
                                "minIndex < 0 and row found in chunk file " + i + " : " + fileRows.get(i));
                    }
                    someFileStillHasRows = true;
                    break;
                }
            }

            // check the actual files one more time
            if (!someFileStillHasRows) {
                //write the last one not covered above
                for (int i = 0; i < fileRows.size(); i++) {
                    if (fileRows.get(i) == null) {
                        line = mergefbr.get(i).readLine();
                        if (line != null) {
                            someFileStillHasRows = true;
                            fileRows.set(i, line);
                        }
                    }
                }
            }
        }

        // close all the files
        bw.close();
        for (BufferedReader br : mergefbr) {
            br.close();
        }
        for (FileReader fr : mergefr) {
            fr.close();
        }
    } catch (Exception ex) {
        LOG.error("Exception merging the sorted files", ex);
        throw new RuntimeException("Exception merging the sorted files", ex);
    }
}

From source file:org.apache.sling.resourcebuilder.test.ResourceAssertions.java

/** Assert that a file exists and verify its properties. */
public Resource assertFile(String path, String mimeType, String expectedContent, Long lastModified,
        Comparator<Long> lastModifiedComparator) throws IOException {
    final Resource r = assertResource(path);
    assertNotNull("Expecting resource to exist:" + path, r);

    // Files are stored according to the standard JCR structure
    final ValueMap fileVm = r.adaptTo(ValueMap.class);
    assertNotNull("Expecting ValueMap for " + r.getPath(), fileVm);
    assertEquals("Expecting an nt:file at " + r.getPath(), ResourceBuilderImpl.NT_FILE,
            fileVm.get(ResourceBuilderImpl.JCR_PRIMARYTYPE));
    final Resource jcrContent = r.getChild(ResourceBuilderImpl.JCR_CONTENT);
    assertNotNull("Expecting subresource:" + ResourceBuilderImpl.JCR_CONTENT, jcrContent);
    final ValueMap vm = jcrContent.adaptTo(ValueMap.class);
    assertNotNull("Expecting ValueMap for " + jcrContent.getPath(), vm);
    assertEquals("Expecting nt:Resource type for " + jcrContent.getPath(), ResourceBuilderImpl.NT_RESOURCE,
            vm.get(ResourceBuilderImpl.JCR_PRIMARYTYPE));
    assertEquals("Expecting the correct mime-type", mimeType, vm.get(ResourceBuilderImpl.JCR_MIMETYPE));
    assertEquals("Expecting the correct last modified", 0,
            lastModifiedComparator.compare(lastModified, getLastModified(vm)));

    final InputStream is = vm.get(ResourceBuilderImpl.JCR_DATA, InputStream.class);
    assertNotNull("Expecting InputStream property on nt:resource:" + ResourceBuilderImpl.JCR_DATA, is);
    final String content = readFully(is);
    assertTrue("Expecting content to contain " + expectedContent, content.contains(expectedContent));

    return r;/* w w  w.  j  av  a  2s  .c om*/
}

From source file:org.apache.carbondata.core.indexstore.blockletindex.BlockletDataMap.java

/**
 * Binary search used to get the last tentative block  based on
 * search key//from w  w w .  ja v  a  2 s. c  om
 *
 * @param key search key
 * @return first tentative block
 */
private int findEndIndex(DataMapRow key, Comparator<DataMapRow> comparator) {
    int childNodeIndex;
    int low = 0;
    int high = memoryDMStore.getRowCount() - 1;
    int mid = 0;
    int compareRes = -1;
    //
    while (low <= high) {
        mid = (low + high) >>> 1;
        // compare the entries
        compareRes = comparator.compare(key, memoryDMStore.getDataMapRow(mid));
        if (compareRes < 0) {
            high = mid - 1;
        } else if (compareRes > 0) {
            low = mid + 1;
        } else {
            int currentPos = mid;
            // if key is matched then get the first entry
            while (currentPos + 1 < memoryDMStore.getRowCount()
                    && comparator.compare(key, memoryDMStore.getDataMapRow(currentPos + 1)) == 0) {
                currentPos++;
            }
            mid = currentPos;
            break;
        }
    }
    // if compare result is less than zero then we
    // and mid is more than 0 then we need to previous block as duplicates
    // record can be present
    if (compareRes < 0) {
        if (mid > 0) {
            mid--;
        }
        childNodeIndex = mid;
    } else {
        childNodeIndex = mid;
    }
    return childNodeIndex;
}

From source file:org.apache.carbondata.core.indexstore.blockletindex.BlockletDataMap.java

/**
 * Binary search used to get the first tentative index row based on
 * search key/*from w w  w . j a v a2s  .c  o m*/
 *
 * @param key search key
 * @return first tentative block
 */
private int findStartIndex(DataMapRow key, Comparator<DataMapRow> comparator) {
    int childNodeIndex;
    int low = 0;
    int high = memoryDMStore.getRowCount() - 1;
    int mid = 0;
    int compareRes = -1;
    //
    while (low <= high) {
        mid = (low + high) >>> 1;
        // compare the entries
        compareRes = comparator.compare(key, memoryDMStore.getDataMapRow(mid));
        if (compareRes < 0) {
            high = mid - 1;
        } else if (compareRes > 0) {
            low = mid + 1;
        } else {
            // if key is matched then get the first entry
            int currentPos = mid;
            while (currentPos - 1 >= 0
                    && comparator.compare(key, memoryDMStore.getDataMapRow(currentPos - 1)) == 0) {
                currentPos--;
            }
            mid = currentPos;
            break;
        }
    }
    // if compare result is less than zero then we
    // and mid is more than 0 then we need to previous block as duplicates
    // record can be present
    if (compareRes < 0) {
        if (mid > 0) {
            mid--;
        }
        childNodeIndex = mid;
    } else {
        childNodeIndex = mid;
    }
    // get the leaf child
    return childNodeIndex;
}

From source file:jetbrains.buildServer.clouds.azure.asm.connector.AzureApiConnector.java

public Promise<Map<String, String>, Throwable, Void> listVmSizesAsync() {
    return myManager.when(myManagementClient.getRoleSizesOperations().listAsync())
            .then(new DonePipe<RoleSizeListResponse, Map<String, String>, Throwable, Void>() {
                @Override//from  ww w .j a  va2  s. com
                public Promise<Map<String, String>, Throwable, Void> pipeDone(RoleSizeListResponse roleSizes) {
                    final Comparator<String> comparator = new AlphaNumericStringComparator();
                    final List<RoleSizeListResponse.RoleSize> sizes = roleSizes.getRoleSizes();
                    Collections.sort(sizes, new Comparator<RoleSizeListResponse.RoleSize>() {
                        @Override
                        public int compare(RoleSizeListResponse.RoleSize o1, RoleSizeListResponse.RoleSize o2) {
                            final String size1 = o1.getName();
                            final String size2 = o2.getName();
                            return comparator.compare(size1, size2);
                        }
                    });

                    final Map<String, String> map = new LinkedHashMap<>();
                    for (RoleSizeListResponse.RoleSize roleSize : sizes) {
                        map.put(roleSize.getName(), roleSize.getLabel());
                    }

                    return new DeferredObject<Map<String, String>, Throwable, Void>().resolve(map);
                }
            });
}

From source file:org.artifactory.build.BuildServiceImpl.java

@Override
public List<BuildRun> getAllPreviousBuilds(String buildName, String buildNumber, String buildStarted) {
    final BuildRun currentBuildRun = getTransactionalMe().getBuildRun(buildName, buildNumber, buildStarted);
    Set<BuildRun> buildRuns = searchBuildsByName(buildName);
    final Comparator<BuildRun> buildNumberComparator = BuildRunComparators.getBuildStartDateComparator();
    Iterables.removeIf(buildRuns, new Predicate<BuildRun>() {
        @Override//  ww w.j av  a 2  s  .c o  m
        public boolean apply(@Nullable BuildRun input) {
            // Remove all builds equals or after the current one
            return buildNumberComparator.compare(currentBuildRun, input) <= 0;
        }
    });

    List<BuildRun> buildRunsList = Lists.newArrayList(buildRuns);
    Comparator<BuildRun> reverseComparator = Collections.reverseOrder(buildNumberComparator);
    Collections.sort(buildRunsList, reverseComparator);

    return buildRunsList;
}

From source file:org.kuali.kfs.gl.batch.BatchSortUtil.java

private static void mergeFiles(File tempSortDir, int numFiles, String outputFileName,
        Comparator<String> comparator) {
    try {/* w w w.  j av a  2 s . c  om*/
        ArrayList<FileReader> mergefr = new ArrayList<FileReader>(numFiles);
        ArrayList<BufferedReader> mergefbr = new ArrayList<BufferedReader>(numFiles);
        // temp buffer for writing - contains the minimum record from each file
        ArrayList<String> fileRows = new ArrayList<String>(numFiles);

        BufferedWriter bw = new BufferedWriter(new FileWriter(outputFileName));
        //LOG.info("Successfully opened output file " + outputFileName);

        boolean someFileStillHasRows = false;

        // Iterate over all the files, getting the first line in each file
        for (int i = 0; i < numFiles; i++) {
            // open a file reader for each file
            mergefr.add(new FileReader(new File(tempSortDir, "chunk_" + i)));
            mergefbr.add(new BufferedReader(mergefr.get(i)));

            // get the first row
            String line = mergefbr.get(i).readLine();
            if (line != null) {
                fileRows.add(line);
                someFileStillHasRows = true;
            } else {
                fileRows.add(null);
            }
        }

        while (someFileStillHasRows) {
            String min = null;
            int minIndex = 0; // index of the file with the minimum record

            // init for later compare - assume the first file has the minimum
            String line = fileRows.get(0);
            if (line != null) {
                min = line;
                minIndex = 0;
            } else {
                min = null;
                minIndex = -1;
            }

            // determine the minimum record of the top lines of each file
            // check which one is min
            for (int i = 1; i < fileRows.size(); i++) {
                line = fileRows.get(i);
                if (line != null) {
                    if (min != null) {
                        if (comparator.compare(line, min) < 0) {
                            minIndex = i;
                            min = line;
                        }
                    } else {
                        min = line;
                        minIndex = i;
                    }
                }
            }

            if (minIndex < 0) {
                someFileStillHasRows = false;
            } else {
                // write to the sorted file
                bw.append(fileRows.get(minIndex)).append('\n');

                // get another row from the file that had the min
                line = mergefbr.get(minIndex).readLine();
                if (line != null) {
                    fileRows.set(minIndex, line);
                } else { // file is out of rows, set to null so it is ignored
                    fileRows.set(minIndex, null);
                }
            }
            // check if one still has rows
            for (int i = 0; i < fileRows.size(); i++) {
                someFileStillHasRows = false;
                if (fileRows.get(i) != null) {
                    if (minIndex < 0) {
                        throw new RuntimeException(
                                "minIndex < 0 and row found in chunk file " + i + " : " + fileRows.get(i));
                    }
                    someFileStillHasRows = true;
                    break;
                }
            }

            // check the actual files one more time
            if (!someFileStillHasRows) {
                //write the last one not covered above
                for (int i = 0; i < fileRows.size(); i++) {
                    if (fileRows.get(i) == null) {
                        line = mergefbr.get(i).readLine();
                        if (line != null) {
                            someFileStillHasRows = true;
                            fileRows.set(i, line);
                        }
                    }
                }
            }
        }

        // close all the files
        bw.close();
        //LOG.info("Successfully closed output file " + outputFileName);

        for (BufferedReader br : mergefbr) {
            br.close();
        }
        for (FileReader fr : mergefr) {
            fr.close();
        }
    } catch (Exception ex) {
        LOG.error("Exception merging the sorted files", ex);
        throw new RuntimeException("Exception merging the sorted files", ex);
    }
}