Example usage for java.lang Long compare

List of usage examples for java.lang Long compare

Introduction

In this page you can find the example usage for java.lang Long compare.

Prototype

public static int compare(long x, long y) 

Source Link

Document

Compares two long values numerically.

Usage

From source file:com.offbynull.voip.kademlia.GraphHelper.java

private void setupRoutingTreeGraph(Context ctx) {
    IdXorMetricComparator idComparator = new IdXorMetricComparator(baseId);

    Map<BitString, Point> processedPrefixes = new HashMap<>(); // prefix -> position on graph
    addRootToGraph(ctx, processedPrefixes);
    routeTreePrefixToIds.put(BitString.createFromString(""), new TreeSet<>(idComparator)); // special case for empty prefix

    LinkedList<BitString> tempPrefixes = new LinkedList<>(routerBucketPrefixes);

    double maxYPosition = Double.MIN_VALUE;
    while (true) {
        // Get next prefixes
        ArrayList<BitString> nextLevelPrefixes = removePrefixesForNextLevel(tempPrefixes);
        if (nextLevelPrefixes.isEmpty()) {
            break;
        }//from w  ww .  j a  va2 s  . co  m

        // Find parent
        int bitLengthOfNextLevelPrefixes = nextLevelPrefixes.get(0).getBitLength();
        BitString parentPrefix = getParentPrefix(processedPrefixes.keySet(), nextLevelPrefixes.get(0));
        Point parentPoint = processedPrefixes.get(parentPrefix);

        // Calculate number of bits after parent prefix (the bits to display)
        int newBitsOffset = parentPrefix.getBitLength();
        int newBitsLength = bitLengthOfNextLevelPrefixes - parentPrefix.getBitLength();

        // Calculate starting x and y positions
        double numBranches = 1 << newBitsLength;
        double missingBitLength = baseId.getBitLength() - bitLengthOfNextLevelPrefixes;
        double ySpreadAtLevel = Y_SPREAD * (missingBitLength + 1.0);
        double xSpreadAtLevel = X_SPREAD * (missingBitLength + 1.0);
        double yPosition = parentPoint.y + ySpreadAtLevel; // nodes right below the parent
        double xPosition = parentPoint.x - xSpreadAtLevel * (numBranches - 1.0) / 2.0; // nodes x-centered on parent

        // special-case for netLevelPrefixes where prefix for our baseId doesn't exist... this is the branch that falls further down
        //
        // e.g. If you're 000, prefixes will be 1, 01, 001, 000... but for each of those you'll want to show the falling-thru prefix as
        // well.. for example...
        //
        //                                    /\
        //        (NOT STATED IN PREFIXES) 0 /  \ 1
        //                                  /\
        //     (NOT STATED IN PREFIXES) 00 /  \ 01
        //                                /\
        //      (EXISTS IN PREFIXES) 000 /  \ 001
        //
        // Note that 000 exists, but 00 and 0 don't.
        BitString baseIdPortion = baseId.getBitString().getBits(0, bitLengthOfNextLevelPrefixes);
        if (!nextLevelPrefixes.contains(baseIdPortion)) {
            nextLevelPrefixes.add(baseIdPortion);
        }

        // Make sure smallest branch is always to the left-most by sorting
        Collections.sort(nextLevelPrefixes,
                (x, y) -> Long.compare(x.getBitsAsLong(newBitsOffset, newBitsLength),
                        y.getBitsAsLong(newBitsOffset, newBitsLength)));

        // Add prefixes from routing tree
        for (BitString nextPrefix : nextLevelPrefixes) {
            routeTreePrefixToIds.put(nextPrefix, new TreeSet<>(idComparator));

            addPrefixToGraph(nextPrefix, newBitsOffset, newBitsLength, xPosition, yPosition, ctx, parentPrefix,
                    processedPrefixes);
            xPosition += xSpreadAtLevel;
        }

        // Update max Y position
        maxYPosition = Math.max(maxYPosition, yPosition);
    }
}

From source file:ch.kanti_baden.pu_marc_14b.traffictimewaste.SORT_TYPE.java

private static Post[] sortPosts(Post[] posts) {
    Comparator<Post> comparator = null;
    switch (SORT_TYPE.values()[sortType]) {
    case NEWEST://from  www  .  jav  a2  s .co m
        comparator = new Comparator<Post>() {
            @Override
            public int compare(Post post, Post t1) {
                return Long.compare(t1.postedAtMillis, post.postedAtMillis);
            }
        };
        break;
    case OLDEST:
        comparator = new Comparator<Post>() {
            @Override
            public int compare(Post post, Post t1) {
                return Long.compare(post.postedAtMillis, t1.postedAtMillis);
            }
        };
        break;
    case UPVOTES:
        comparator = new Comparator<Post>() {
            @Override
            public int compare(Post post, Post t1) {
                return Integer.compare(t1.votesUp - t1.votesDown, post.votesUp - post.votesDown);
            }
        };
        break;
    case DOWNVOTES:
        comparator = new Comparator<Post>() {
            @Override
            public int compare(Post post, Post t1) {
                return Integer.compare(t1.votesDown - t1.votesUp, post.votesDown - post.votesUp);
            }
        };
        break;
    }

    Arrays.sort(posts, comparator);
    return posts;
}

From source file:org.wso2.carbon.analytics.dataservice.core.indexing.sort.RecordSortUtils.java

private static int compareValues(AnalyticsSchema.ColumnType type, Object value1, Object value2)
        throws AnalyticsException {
    int compareInt;
    switch (type) {
    case STRING://from   w w  w.ja  v a  2 s .  co m
        compareInt = ((String) value1).compareTo(((String) value2));
        break;
    case INTEGER:
        compareInt = Integer.compare((Integer) value1, (Integer) value2);
        break;
    case LONG:
        compareInt = Long.compare((Long) value1, (Long) value2);
        break;
    case FLOAT:
        compareInt = Float.compare((Float) value1, (Float) value2);
        break;
    case DOUBLE:
        compareInt = Double.compare((Double) value1, (Double) value2);
        break;
    case BOOLEAN:
        compareInt = Boolean.compare((Boolean) value1, (Boolean) value2);
        break;
    default:
        throw new AnalyticsException("Cannot sort values of type: " + type);
    }
    return compareInt;
}

From source file:org.apache.cassandra.db.lifecycle.LogFile.java

private static void deleteRecordFiles(LogRecord record) {
    List<File> files = record.getExistingFiles();

    // we sort the files in ascending update time order so that the last update time
    // stays the same even if we only partially delete files, see comment in isInvalid()
    files.sort((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified()));

    files.forEach(LogTransaction::delete);
}

From source file:org.janusgraph.graphdb.idmanagement.VariableLongTest.java

@Test
public void byteOrderPreservingPositiveBackward() {
    long[] scalingFactors = { Long.MAX_VALUE, 1000, 1000000000l };
    for (int t = 0; t < 10000000; t++) {
        StaticBuffer[] b = new StaticBuffer[2];
        long[] l = new long[2];
        for (int i = 0; i < 2; i++) {
            l[i] = randomPosLong(scalingFactors[random.nextInt(scalingFactors.length)]);
            WriteBuffer out = new WriteByteBuffer(11);
            VariableLong.writePositiveBackward(out, l[i]);
            b[i] = out.getStaticBuffer();
            ReadBuffer res = b[i].asReadBuffer();
            res.movePositionTo(res.length());
            assertEquals(l[i], VariableLong.readPositiveBackward(res));
        }//from www.ja  v a2 s.c om
        //            System.out.println(l[0] + " vs " + l[1]);
        assertEquals(Math.signum(Long.compare(l[0], l[1])), Math.signum(b[0].compareTo(b[1])), 0.01);
    }

}

From source file:com.google.uzaygezen.core.LongBitVector.java

@Override
public int compareTo(BitVector o) {
    checkSize(o);//from  w w  w .j  av  a 2 s  .co m
    final int cmp;
    // optimisation
    if (o.size() <= 64) {
        // 0, positives, Long.MAX_VALUE, Long.MIN_VALUE, negatives, -1
        long x = data + Long.MIN_VALUE;
        long y = o.toExactLong() + Long.MIN_VALUE;
        cmp = Long.compare(x, y);
        assert Integer.signum(cmp) == Integer
                .signum(BitSetComparator.INSTANCE.compare(toBitSet(), o.toBitSet()));
    } else {
        cmp = BitSetComparator.INSTANCE.compare(toBitSet(), o.toBitSet());
    }
    return cmp;
}

From source file:org.mitre.mpf.wfm.data.entities.transients.Track.java

@Override
public int compareTo(Track other) {
    int comparisonResult;
    if (other == null) {
        comparisonResult = 1; // non-null > null
    } else if ((comparisonResult = Long.compare(jobId, other.jobId)) == 0
            && (comparisonResult = Long.compare(mediaId, other.mediaId)) == 0
            && (comparisonResult = Integer.compare(stageIndex, other.stageIndex)) == 0
            && (comparisonResult = Integer.compare(actionIndex, other.actionIndex)) == 0
            && (comparisonResult = Integer.compare(startOffsetFrameInclusive,
                    other.startOffsetFrameInclusive)) == 0
            && (comparisonResult = Integer.compare(endOffsetFrameInclusive, other.endOffsetFrameInclusive)) == 0
            && (comparisonResult = Integer.compare(startOffsetTimeInclusive,
                    other.startOffsetTimeInclusive)) == 0
            && (comparisonResult = Integer.compare(endOffsetTimeInclusive, other.endOffsetTimeInclusive)) == 0
            && (comparisonResult = nullSafeCompare(type, other.type)) == 0
            && (comparisonResult = nullSafeCompare(exemplar, other.exemplar)) == 0
            && (comparisonResult = compareDetections(detections, other.detections)) == 0) {
        comparisonResult = 0;//from   w ww .  j  av a2  s  . com
    }

    return comparisonResult;
}

From source file:org.opencb.hpg.bigdata.core.converters.variation.VariantContext2VariantConverter.java

@Override
public Variant forward(VariantContext variantContext) {
    Variant gaVariant = new Variant();

    gaVariant.setVariantSetId(variantSetId);

    gaVariant.setId(variantContext.getContig() + ":" + translateStartPosition(variantContext) + ":"
            + variantContext.getReference().getBaseString() + ":"
            + StringUtils.join(variantContext.getAlternateAlleles(), ","));
    // Assumed to be related to the avro record
    long currTime = System.currentTimeMillis();
    gaVariant.setCreated(currTime);//from  w w  w  .ja  v  a2 s .c  o  m
    gaVariant.setUpdated(currTime);

    /* VCF spec (1-Based):
     *  -> POS - position: The reference position, with the 1st base having position 1.
     *  -> TODO: Telomeres are indicated by using positions 0 or N+1
     * GA4GH spec
     *  -> (0-Based)
     */
    gaVariant.setReferenceName(variantContext.getContig());
    gaVariant.setStart(translateStartPosition(variantContext));

    /* 0-based, exclusive end position [start,end) */
    /* 1-based, inclusive end position [start,end] */
    gaVariant.setEnd((long) variantContext.getEnd());
    List<String> nameList = Collections.emptyList();

    if (StringUtils.isNotBlank(variantContext.getID())) {
        nameList = Arrays.asList(variantContext.getID().split(VCFConstants.ID_FIELD_SEPARATOR));
    }

    gaVariant.setNames(nameList);

    /* Classic mode */
    // Reference
    Allele refAllele = variantContext.getReference();
    gaVariant.setReferenceBases(refAllele.getBaseString());

    assert Long.compare(gaVariant.getEnd() - gaVariant.getStart(), gaVariant.getReferenceBases().length()) == 0;

    // Alt
    List<Allele> altAllele = variantContext.getAlternateAlleles();
    List<String> altList = new ArrayList<>(altAllele.size());
    for (Allele allele : altAllele) {
        altList.add(allele.getBaseString());
    }
    gaVariant.setAlternateBases(altList);

    /* Graph mode */
    // NOT supported
    // gaVariant.setAlleleIds(value);

    // INFO
    Map<String, List<String>> info = convertInfo(variantContext);
    gaVariant.setInfo(info);

    // QUAL
    info.put(VCF_QUAL_COLUMN, Collections.singletonList(Double.toString(variantContext.getPhredScaledQual())));

    //  FILTER
    Set<String> filter = variantContext.getFilters();
    if (filter.isEmpty()) {
        info.put(VCF_FILTER_COLUMN, Collections.singletonList(VCFConstants.PASSES_FILTERS_v4));
    } else {
        info.put(VCF_FILTER_COLUMN, new ArrayList<>(filter));
    }

    // Genotypes (Call's)

    gaVariant.setCalls(convertCalls(variantContext));

    return gaVariant;
}

From source file:com.android.tv.data.Program.java

@Override
public int compareTo(@NonNull Program other) {
    return Long.compare(mStartTimeUtcMillis, other.mStartTimeUtcMillis);
}

From source file:ubic.gemma.web.controller.expression.experiment.ExpressionExperimentDataFetchController.java

/**
 * @param file a directory to scan//from  w  w  w .j av a  2 s.c o m
 * @return the file in the directory that was last modified, or null, if such file doesn't exist or is not readable.
 */
private File getNewestFile(File file) {
    File[] files = file.listFiles();
    if (files != null && files.length > 0) {
        List<File> fList = Arrays.asList(files);

        // Sort by last modified, we only want the newest file
        Collections.sort(fList, new Comparator<File>() {
            @Override
            public int compare(File file, File t1) {
                return Long.compare(file.lastModified(), t1.lastModified());
            }
        });

        if (fList.get(0).canRead()) {
            return fList.get(0);
        }
    }
    return null;
}