类com.google.common.collect.ComparisonChain源码实例Demo

下面列出了怎么用com.google.common.collect.ComparisonChain的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: dsl-devkit   文件: CheckContextsGenerator.java
/**
 * This method sorts all contexts alphabetically so that the file always gets generated in the same order.
 *
 * @param model
 *          context model
 */
private void sortAllContexts(final CtxHelpModel model) {
  Ordering<CtxHelpContext> ordering = Ordering.from((a, b) -> ComparisonChain.start().compare(a.getId(), b.getId()).result());
  List<CtxHelpContext> allContexts = Lists.newArrayList(Iterables.filter(model.getCtxHelpRoot().getChildren(), CtxHelpContext.class));
  List<CtxHelpContext> expectedContexts = ordering.sortedCopy(allContexts);
  CtxHelpRoot root = model.getCtxHelpRoot();

  if (!expectedContexts.equals(allContexts)) {
    for (int i = 0; i < expectedContexts.size(); i++) {
      CtxHelpContext expected = expectedContexts.get(i);
      CtxHelpContext actual = allContexts.get(i);
      if (!actual.getId().equals(expected.getId())) {
        root.swap(actual, expected);
        allContexts.set(allContexts.indexOf(expected), actual);
        allContexts.set(i, expected);
      }
    }
  }
}
 
源代码2 项目: emodb   文件: ClaimCountTask.java
@Override
public void execute(ImmutableMultimap<String, String> parameters, PrintWriter output) throws Exception {
    Map<String, Long> map = _eventStore.snapshotClaimCounts();

    if (map.isEmpty()) {
        output.println("no claims");
        return;
    }

    // Sort the entries in the map from biggest to smallest.
    List<Map.Entry<String,Long>> entries = Lists.newArrayList(map.entrySet());
    Collections.sort(entries, new Comparator<Map.Entry<String, Long>>() {
        @Override
        public int compare(Map.Entry<String, Long> e1, Map.Entry<String, Long> e2) {
            return ComparisonChain.start()
                    .compare(e2.getValue(), e1.getValue())   // Sort counts descending
                    .compare(e1.getKey(), e2.getKey())       // Sort channel names ascending
                    .result();
        }
    });

    // Print a formatted table with two columns.
    for (Map.Entry<String, Long> entry : entries) {
        output.println(Strings.padStart(entry.getValue().toString(), 9, ' ') + "  " + entry.getKey());
    }
}
 
源代码3 项目: scalardb   文件: BlobValue.java
@Override
public int compareTo(BlobValue o) {
  if (bytes.isPresent() && o.bytes.isPresent()) {
    return ComparisonChain.start()
        .compare(bytes.get(), o.bytes.get())
        .compare(this.name, o.name)
        .result();
  } else {
    // either bytes or o.bytes is empty
    if (bytes.isPresent()) {
      return 1;
    } else if (o.bytes.isPresent()) {
      return -1;
    } else {
      return 0;
    }
  }
}
 
源代码4 项目: Singularity   文件: SingularityTaskHistoryQuery.java
public Comparator<SingularityTaskIdHistory> getComparator() {
  final OrderDirection localOrderDirection = orderDirection.orElse(OrderDirection.DESC);

  return new Comparator<SingularityTaskIdHistory>() {

    @Override
    public int compare(SingularityTaskIdHistory o1, SingularityTaskIdHistory o2) {
      ComparisonChain chain = ComparisonChain.start();

      if (localOrderDirection == OrderDirection.ASC) {
        chain = chain.compare(o1.getUpdatedAt(), o2.getUpdatedAt());
      } else {
        chain = chain.compare(o2.getUpdatedAt(), o1.getUpdatedAt());
      }

      return chain
        .compare(o1.getTaskId().getRequestId(), o2.getTaskId().getRequestId())
        .result();
    }
  };
}
 
源代码5 项目: brooklyn-server   文件: BrooklynImageChooser.java
/** @deprecated since 0.7.0; kept for persisted state backwards compatibility */
@Deprecated
@SuppressWarnings("unused")
private static Ordering<Image> orderingWithDefaultsDeprecated(final Ordering<Image> primaryOrdering) {
    return new Ordering<Image>() {
        @Override
        public int compare(Image left, Image right) {
            return ComparisonChain.start()
                .compare(left, right, primaryOrdering)
                // fall back to default strategy otherwise, except preferring *non*-null values
                // TODO suggest to use NaturalOrderComparator (so 10>9) then order by:
                // 1) `name.replaceAll("([^0-9]+)", " ")` 
                // 2) shortest non-empty name
                // 3) version (NaturalOrderComparator, prefer last)
                // 4) name (NaturalOrderComparator, prefer last)
                // 5) other fields (NaturalOrderComparator, prefer last)
                .compare(left.getName(), right.getName(), Ordering.<String> natural().nullsFirst())
                .compare(left.getVersion(), right.getVersion(), Ordering.<String> natural().nullsFirst())
                .compare(left.getDescription(), right.getDescription(), Ordering.<String> natural().nullsFirst())
                .compare(left.getOperatingSystem().getName(), right.getOperatingSystem().getName(), Ordering.<String> natural().nullsFirst())
                .compare(left.getOperatingSystem().getVersion(), right.getOperatingSystem().getVersion(), Ordering.<String> natural().nullsFirst())
                .compare(left.getOperatingSystem().getDescription(), right.getOperatingSystem().getDescription(), Ordering.<String> natural().nullsFirst())
                .compare(left.getOperatingSystem().getArch(), right.getOperatingSystem().getArch(), Ordering.<String> natural().nullsFirst()).result();
        }
    };
}
 
源代码6 项目: metanome-algorithms   文件: DatatypeLong.java
public DatatypeLong(final Comparator<Long> comparator) {
  this.specificType = type.LONG;

  if (comparator == null) {
    this.indexedComparator = new Comparator<RowIndexedLongValue>() {

      @Override
      public int compare(final RowIndexedLongValue o1, final RowIndexedLongValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.natural().nullsFirst()).result();
      }

    };
  } else {
    this.indexedComparator = new Comparator<RowIndexedLongValue>() {

      @Override
      public int compare(final RowIndexedLongValue o1, final RowIndexedLongValue o2) {
        return ComparisonChain.start()
            .compare(o1.value, o2.value, Ordering.from(comparator).nullsFirst()).result();
      }

    };
  }

}
 
源代码7 项目: guacamole-client   文件: MySQLVersion.java
/**
 * Returns whether this version is at least as recent as the given version.
 *
 * @param version
 *     The version to compare against.
 *
 * @return
 *     true if the versions are associated with the same database server
 *     type (MariaDB vs. MySQL) and this version is at least as recent as
 *     the given version, false otherwise.
 */
public boolean isAtLeast(MySQLVersion version) {

    // If the databases use different version numbering schemes, the
    // version numbers are not comparable
    if (isMariaDB != version.isMariaDB)
        return false;

    // Compare major, minor, and patch number in order of precedence
    return ComparisonChain.start()
            .compare(major, version.major)
            .compare(minor, version.minor)
            .compare(patch, version.patch)
            .result() >= 0;

}
 
源代码8 项目: tac-kbp-eal   文件: ByJustificationLocation.java
@Override
public int compare(final Answerable left, final Answerable right) {
  final Optional<Response> earliestLeftResponse = earliestResponse(left);
  final Optional<Response> earliestRightResponse = earliestResponse(right);

  if (earliestLeftResponse.isPresent()) {
    if (earliestRightResponse.isPresent()) {
      return ComparisonChain.start()
          .compare(earliestLeftResponse.get(), earliestRightResponse.get(),
              Response.ByJustificationLocation)
          .compare(left, right)
          .result();
    } else {
      return -1;
    }
  } else if (earliestRightResponse.isPresent()) {
    return 1;
  } else {
    return left.compareTo(right);
  }
}
 
源代码9 项目: aegisthus   文件: AegisthusKey.java
public int compareTo(@Nonnull AegisthusKey other, Comparator<ByteBuffer> nameComparator) {
    // This is a workaround for comparators not handling nulls properly
    // The case where name or timestamp is null should only happen when there has been a delete
    int result = this.key.compareTo(other.key);
    if (result != 0) {
        return result;
    }

    result = this.sourcePath.compareTo(other.sourcePath);
    if (result != 0) {
        return result;
    }

    if (this.name == null || this.timestamp == null) {
        return -1;
    } else if (other.name == null || other.timestamp == null) {
        return 1;
    }

    return ComparisonChain.start()
            .compare(this.name, other.name, nameComparator)
            .compare(this.timestamp, other.timestamp)
            .result();
}
 
源代码10 项目: sql-layer   文件: TypesRegistryServiceImpl.java
private Object typesDescriptors() {
    List<Map<String,Comparable<?>>> result = new ArrayList<>(tClasses.size());
    for (TClass tClass : tClasses) {
        Map<String,Comparable<?>> map = new LinkedHashMap<>();
        buildTName("bundle", "name", tClass, map);
        map.put("category", tClass.name().categoryName());
        map.put("internalVersion", tClass.internalRepresentationVersion());
        map.put("serializationVersion", tClass.serializationVersion());
        map.put("fixedSize", tClass.hasFixedSerializationSize() ? tClass.fixedSerializationSize() : null);
        result.add(map);
    }
    Collections.sort(result, new Comparator<Map<String, Comparable<?>>>() {
        @Override
        public int compare(Map<String, Comparable<?>> o1, Map<String, Comparable<?>> o2) {
            return ComparisonChain.start()
                    .compare(o1.get("bundle"), o2.get("bundle"))
                    .compare(o1.get("category"), o2.get("category"))
                    .compare(o1.get("name"), o2.get("name"))
                    .result();
        }
    });
    return result;
}
 
源代码11 项目: buck   文件: CxxLinkGroupMappingTarget.java
@Override
public int compareTo(CxxLinkGroupMappingTarget that) {
  if (this == that) {
    return 0;
  }

  int labelComparison = compareLabelPattern(that);
  if (labelComparison != 0) {
    return labelComparison;
  }

  return ComparisonChain.start()
      .compare(this.getBuildTarget(), that.getBuildTarget())
      .compare(this.getTraversal(), that.getTraversal())
      .result();
}
 
List<TabListEntry> getVisibleEntries() {
    if (visibleEntries == null) {
        List<TabListEntry> entries = new ArrayList<>(this.entries.values());
        entries.sort(new Comparator<TabListEntry>() {
            @Override
            public int compare(TabListEntry o1, TabListEntry o2) {
                return ComparisonChain.start().compareTrueFirst(o1.getGamemode() != 3, o2.getGamemode() != 3)
                        .compare(MoreObjects.firstNonNull(playerToTeamMap.get(o1.getUsername()), ""), MoreObjects.firstNonNull(playerToTeamMap.get(o2.getUsername()), ""))
                        .compare(o1.getUsername(), o2.getUsername()).result();
            }
        });
        if (entries.size() > 80) {
            entries = entries.subList(0, 80);
        }
        visibleEntries = Collections.unmodifiableList(entries);
    }
    return visibleEntries;
}
 
源代码13 项目: data-polygamy   文件: FrameworkUtils.java
@Override
// TODO: is this efficient enough? It seems slow
public int compareTo(MultipleSpatioTemporalWritable arg0) {
    spatialComp = arg0.getSpatial();
    temporalComp = arg0.getTemporal();
    ch = ComparisonChain.start();
    
    // assuming they have the same size
    for (int i = 0; i < this.spatial.length; i++)
        ch = ch.compare(this.spatial[i], spatialComp[i]);

    for (int i = 0; i < this.temporal.length; i++)
        ch = ch.compare(this.temporal[i], temporalComp[i]);
    
    return ch.result();
}
 
源代码14 项目: crate   文件: FunctionIdent.java
@Override
public int compareTo(FunctionIdent o) {
    return ComparisonChain.start()
        .compare(fqnName, o.fqnName)
        .compare(argumentTypes, o.argumentTypes, Ordering.<DataType<?>>natural().lexicographical())
        .result();
}
 
源代码15 项目: tac-kbp-eal   文件: _Response.java
@Override
public int compare(final Response left, final Response right) {
  return ComparisonChain.start()
      .compare(left.docID().toString(), right.docID().toString())
      .compare(
          Ordering.natural().sortedCopy(left.predicateJustifications()),
          Ordering.natural().sortedCopy(right.predicateJustifications()),
          Ordering.<CharOffsetSpan>natural().lexicographical())
      .compare(left.baseFiller(), right.baseFiller())
      .compare(left.canonicalArgument().charOffsetSpan(),
          right.canonicalArgument().charOffsetSpan())
      .compare(left.realis(), right.realis())
      .result();
}
 
源代码16 项目: crate   文件: FunctionName.java
@Override
public int compareTo(FunctionName o) {
    return ComparisonChain.start()
        .compare(schema, o.schema)
        .compare(name, o.name)
        .result();
}
 
@Override
public int compare(SemanticHighlightingInformation left, SemanticHighlightingInformation right) {
	//@formatter:off
	return ComparisonChain.start()
		.compare(left.getLine(), right.getLine())
		.result();
	//@formatter:on
}
 
源代码18 项目: The-5zig-Mod   文件: GuiHypixelStats.java
@Override
protected void onKeyType(char character, int key) {
	ITextfield textfield = getTextfieldById(1);
	if (textfield.callIsFocused() && !The5zigMod.getVars().isPlayerNull() && key == Keyboard.KEY_TAB) {
		if (tabWord == null) {
			tabWord = textfield.callGetText().toLowerCase();
		}
		List<NetworkPlayerInfo> tabPlayers = The5zigMod.getVars().getServerPlayers();
		Collections.sort(tabPlayers, new Comparator<NetworkPlayerInfo>() {
			@Override
			public int compare(NetworkPlayerInfo t0, NetworkPlayerInfo t1) {
				return ComparisonChain.start().compare(t0.getGameProfile().getName(), t1.getGameProfile().getName()).result();
			}
		});
		for (Iterator<NetworkPlayerInfo> it = tabPlayers.iterator(); it.hasNext(); ) {
			NetworkPlayerInfo next = it.next();
			if (next.getGameProfile().getName() == null || !next.getGameProfile().getName().toLowerCase().startsWith(tabWord)) {
				it.remove();
			}
		}
		if (!tabPlayers.isEmpty()) {
			tabIndex = tabIndex % tabPlayers.size();
			NetworkPlayerInfo playerInfo = tabPlayers.get(tabIndex);
			textfield.callSetText(playerInfo.getGameProfile().getName());
			tabIndex = (tabIndex + 1) % tabPlayers.size();
		}
	} else {
		tabIndex = 0;
		tabWord = null;
	}
}
 
源代码19 项目: presto   文件: Validator.java
@Override
public int compareTo(ChangedRow that)
{
    return ComparisonChain.start()
            .compare(this.row, that.row, rowComparator(precision))
            .compareFalseFirst(this.changed == Changed.ADDED, that.changed == Changed.ADDED)
            .result();
}
 
源代码20 项目: big-c   文件: AclTransformation.java
@Override
public int compare(AclEntry entry1, AclEntry entry2) {
  return ComparisonChain.start()
    .compare(entry1.getScope(), entry2.getScope(),
      Ordering.explicit(ACCESS, DEFAULT))
    .compare(entry1.getType(), entry2.getType(),
      Ordering.explicit(USER, GROUP, MASK, OTHER))
    .compare(entry1.getName(), entry2.getName(),
      Ordering.natural().nullsFirst())
    .result();
}
 
源代码21 项目: presto   文件: PrioritizedFifoExecutor.java
@Override
public int compareTo(FifoRunnableTask<T> other)
{
    return ComparisonChain.start()
            .compare(this.task, other.task, taskComparator)
            .compare(this.sequenceNumber, other.sequenceNumber)
            .result();
}
 
源代码22 项目: picard   文件: WidthLimitingDecoratorTest.java
@Test
public void testForVcf() throws Exception {

    final Segment entireThing = new Segment(1, 9942);
    final ImmutableList<Segment> expectedSubThings = ImmutableList.of(
            new Segment(1, 1000),
            new Segment(1001, 2000),
            new Segment(2001, 3000),
            new Segment(3001, 4000),
            new Segment(4001, 5000),
            new Segment(5001, 6000),
            new Segment(6001, 7000),
            new Segment(7001, 8000),
            new Segment(8001, 9000),
            new Segment(9001, 9942)
    );

    final VcfFileSegmentGenerator.WidthLimitingDecorator strategy = VcfFileSegmentGenerator.WidthLimitingDecorator.wrapping(new VcfFileSegmentGenerator() {
        @Override
        public Iterable<VcfFileSegment> forVcf(final File vcf) {
            return Collections.singleton((VcfFileSegment) entireThing);
        }
    }, 1000);

    final List<VcfFileSegment> observed = new ArrayList<VcfFileSegment>();
    Iterators.addAll(observed, strategy.forVcf(new File("B")).iterator());
    final Iterator<VcfFileSegment> observedIterator = observed.iterator();
    for (final VcfFileSegment e : expectedSubThings) {
        Assert.assertTrue(observedIterator.hasNext());
        final VcfFileSegment o = observedIterator.next();
        Assert.assertEquals(ComparisonChain.start()
                .compare(o.contig(), e.contig())
                .compare(o.start(), e.start())
                .compare(o.stop(), e.stop())
                .compare(o.vcf(), e.vcf())
                .result(), 0, String.format(String.format("observed=%[email protected]%s:%s-%s  expected=%s", o.vcf(), o.contig(), o.start(), 
                o.stop(), e.toString())));
    }
}
 
源代码23 项目: naturalize   文件: SegmentRenamingSuggestion.java
@Override
public int compareTo(final Suggestion other) {
	return ComparisonChain.start()
			.compare(confidenceGap, other.confidenceGap)
			.compare(identifierName, other.identifierName)
			.compare(scope, other.scope).result();
}
 
源代码24 项目: metron   文件: InMemoryDao.java
private static Comparator<SearchResult> sorted(final List<SortField> fields) {
  return (o1, o2) -> {
    ComparisonChain chain = ComparisonChain.start();
    for(SortField field : fields) {
      Comparable f1 = (Comparable) o1.getSource().get(field.getField());
      Comparable f2 = (Comparable) o2.getSource().get(field.getField());
      chain = chain.compare(f1, f2, new ComparableComparator(field.getSortOrder()));
    }
    return chain.result();
  };
}
 
源代码25 项目: data-polygamy   文件: Min.java
@Override
public int compareTo(Aggregation arg0) {
    Min agg = (Min) arg0;
    return ComparisonChain.start().
            compare(min, agg.getMin()).
            compare(count, agg.getCount()).
            result();
}
 
源代码26 项目: notification   文件: Notification.java
/**
 * Always sort notifications in descending order (largest IDs first)
 *
 * @param that Notification to compare to
 * @return 1 if this greater than that, 0 if this equal to that, or -1 if this less than that
 */
@Override
public int compareTo(final Notification that) {
  return ComparisonChain.start()
      .compare(this.getId(""), that.getId(""), Comparator.reverseOrder())
      .result();
}
 
源代码27 项目: scalardb   文件: Snapshot.java
@Override
public int compareTo(Key o) {
  return ComparisonChain.start()
      .compare(this.namespace, o.namespace)
      .compare(this.table, o.table)
      .compare(this.partitionKey, o.partitionKey)
      .compare(
          this.clusteringKey.orElse(null),
          o.clusteringKey.orElse(null),
          Ordering.natural().nullsFirst())
      .result();
}
 
源代码28 项目: FreeBuilder   文件: QualifiedName.java
@Override
public int compareTo(QualifiedName o) {
  return ComparisonChain.start()
      .compare(packageName, o.packageName)
      .compare(simpleNames, o.simpleNames, Ordering.natural().lexicographical())
      .result();
}
 
源代码29 项目: Singularity   文件: SingularityRequestHistory.java
@Override
public int compareTo(SingularityRequestHistory o) {
  return ComparisonChain
    .start()
    .compare(o.getCreatedAt(), createdAt)
    .compare(request.getId(), o.getRequest().getId())
    .result();
}
 
源代码30 项目: Strata   文件: DummyPointSensitivity.java
@Override
public int compareKey(PointSensitivity other) {
  if (other instanceof DummyPointSensitivity) {
    DummyPointSensitivity otherZero = (DummyPointSensitivity) other;
    return ComparisonChain.start()
        .compare(curveCurrency, otherZero.curveCurrency)
        .compare(currency, otherZero.currency)
        .compare(date, otherZero.date)
        .result();
  }
  return getClass().getSimpleName().compareTo(other.getClass().getSimpleName());
}
 
 同包方法