下面列出了java.util.NavigableSet# contains ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* Calculates the intersection between sets and returns a new set.
*
* @param smaller - First Set
* @param bigger - Second Set
* @return resultSet which is the intersection of these two sets.
*/
private NavigableSet<ContainerID> intersectSets(
final NavigableSet<ContainerID> smaller,
final NavigableSet<ContainerID> bigger) {
Preconditions.checkState(smaller.size() <= bigger.size(),
"This function assumes the first set is lesser or equal to second " +
"set");
final NavigableSet<ContainerID> resultSet = new TreeSet<>();
for (ContainerID id : smaller) {
if (bigger.contains(id)) {
resultSet.add(id);
}
}
return resultSet;
}
/**
* Verifies whether all {@code BigInteger}s in the tested range for which
* {@code isProbablePrime()} returns {@code false} are <i>not</i>
* prime numbers.
*
* @return true if and only if the test succeeds
*/
private static boolean checkNonPrime(NavigableSet<BigInteger> primes,
int certainty) {
int maxPrime = DEFAULT_UPPER_BOUND;
try {
maxPrime = primes.last().intValueExact();
} catch (ArithmeticException e) {
// ignore it
}
// Create a list of non-prime BigIntegers.
SplittableRandom splitRandom = RandomFactory.getSplittableRandom();
List<BigInteger> nonPrimeBigInts = (splitRandom)
.ints(NUM_NON_PRIMES, 2, maxPrime).mapToObj(BigInteger::valueOf)
.filter(b -> !b.isProbablePrime(certainty)).collect(toList());
// If there are any non-probable primes also in the primes list then fail.
boolean failed = nonPrimeBigInts.stream().anyMatch(primes::contains);
// In the event, print which purported non-primes were actually prime.
if (failed) {
for (BigInteger bigInt : nonPrimeBigInts) {
if (primes.contains(bigInt)) {
System.err.println("Prime value thought to be non-prime: " + bigInt);
}
}
}
return !failed;
}
public static void main(String[] args) {
DB db = DBMaker.newMemoryDB().make();
// this is wrong, do not do it !!!
// Map<String,List<Long>> map
//correct way is to use composite set, where 'map key' is primary key and 'map value' is secondary value
NavigableSet<Fun.Tuple2<String,Long>> multiMap = db.getTreeSet("test");
multiMap.add(Fun.t2("aa",1L));
multiMap.add(Fun.t2("aa",2L));
multiMap.add(Fun.t2("aa",3L));
multiMap.add(Fun.t2("bb",1L));
//find all values for a key
for(Long l: Bind.findSecondaryKeys(multiMap, "aa")){
System.out.println("value for key 'aa': "+l);
}
//check if pair exists
boolean found = multiMap.contains(Fun.t2("bb",1L));
System.out.println("Found: " + found);
db.close();
}
/**
* Retrieves the latest version for each provided major version if it is available.
*
* <p>For each provided version, if there is an available version within the major version range
* and {@link MajorVersion#hasStableApi()} returns true, or
* {@link MajorVersion#getStableVersion()} is not in the list of requested versions, that version
* will appear in the returned map. Otherwise, if the {@link MajorVersion#hasStableApi()} returns
* false and there is no available version for {@link MajorVersion#getStableVersion()}, the latest
* version in the Unstable version range will be returned.
*/
public NavigableMap<ArtifactVersion, MajorVersion> getLatestVersions(
NavigableSet<MajorVersion> majorVersions) {
NavigableMap<ArtifactVersion, MajorVersion> result = new TreeMap<>();
Table<MajorVersion, ArtifactVersion, MajorVersion> unstableVersions = HashBasedTable.create();
for (MajorVersion majorVersion : majorVersions) {
ArtifactVersion latestInMajorVersion =
getLatestDataflowDependencyInRange(majorVersion.getVersionRange());
if (latestInMajorVersion != null) {
if (majorVersion.hasStableApi()
|| !majorVersions.contains(majorVersion.getStableVersion())) {
result.put(latestInMajorVersion, majorVersion);
} else {
unstableVersions.put(majorVersion.getStableVersion(), latestInMajorVersion, majorVersion);
}
} else {
// All Major Versions that are unstable and have an associated stable version precede the
// stable major version with the natural ordering, so we will never get a stable version
// before the unstable versions
for (Map.Entry<ArtifactVersion, MajorVersion> unstableVersion :
unstableVersions.row(majorVersion).entrySet()) {
result.put(unstableVersion.getKey(), unstableVersion.getValue());
}
}
}
if (result.isEmpty()) {
result.put(new DefaultArtifactVersion("LATEST"), MajorVersion.ALL);
}
return result;
}
@SuppressWarnings("unchecked")
private <R extends AddressTrie<T>, T extends Address> void testBoundedClone(NavigableSet<T> set) {
// when cloning, the bounds are removed and the out-of-bounds nodes are trimmed from the trie
AddressTrie<T> newTrie;
if(set instanceof AddressTrieSet) {
AddressTrieSet<T> trieSet = (AddressTrieSet<T>) set;
newTrie = trieSet.asTrie();
} else if(set instanceof WrappedMap) {
WrappedMap<T, ?> wrapped = (WrappedMap<T, ?>) set;
newTrie = wrapped.map.asTrie();
} else {
return;
}
if(newTrie.size() != set.size()) {
addFailure("size mismatch, got " + newTrie.size() + " after clone, not " + set.size(), set);
}
// now we check the trie looks like it should
int count = 0;
Iterator<? extends TrieNode<T>> iterator = newTrie.allNodeIterator(true);
while(iterator.hasNext()) {
TrieNode<T> next = iterator.next();
if(next.isAdded()) {
count++;
if(!set.contains(next.getKey())) {
addFailure("failed clone, found " + next + " when iterating, not in set", set);
}
} else {
if(!next.isRoot() && (next.getLowerSubNode() == null || next.getUpperSubNode() == null)) {
addFailure("trie structure flawed below " + next, set);
}
}
}
if(newTrie.size() != count) {
addFailure("size mismatch, got " + count + " when iterating, not " + newTrie.size(), set);
}
}
/**
* Expand a name if it is an unambiguous prefix of an entry in the given set of names
* @param names the reference set of names
* @param prefix the name prefix
* @return the input name, or an unambiguous expansion of it
*/
public static String expandPrefix(NavigableSet<String> names, String prefix) {
String name = prefix;
if (!names.contains(name)) {
// Try a search for unambiguous prefix
final String closest = names.ceiling(prefix);
if (closest != null && closest.startsWith(prefix)) {
final String higher = names.higher(closest);
if (higher == null || !higher.startsWith(prefix)) {
name = closest;
}
}
}
return name;
}
private boolean isColumnIncluded(Cell cell) {
byte[] family = CellUtil.cloneFamily(cell);
if (!familyMap.containsKey(family)) {
return false;
}
NavigableSet<byte[]> set = familyMap.get(family);
if (set == null || set.isEmpty()) {
return true;
}
byte[] qualifier = CellUtil.cloneQualifier(cell);
return set.contains(qualifier);
}
/**
* @param otherAssignments Newest assigmnets.
*
* @return {@code True} when future compared with other, {@code False} otherwise.
*/
public boolean compatibleWith(GridDhtPreloaderAssignments otherAssignments) {
if (isInitial() || ((GridDhtPreloader)grp.preloader()).disableRebalancingCancellationOptimization())
return false;
if (ctx.exchange().lastAffinityChangedTopologyVersion(topVer).equals(
ctx.exchange().lastAffinityChangedTopologyVersion(otherAssignments.topologyVersion()))) {
if (log.isDebugEnabled())
log.debug("Rebalancing is forced on the same topology [grp="
+ grp.cacheOrGroupName() + ", " + "top=" + topVer + ']');
return false;
}
if (otherAssignments.affinityReassign()) {
if (log.isDebugEnabled())
log.debug("Some of owned partitions were reassigned through coordinator [grp="
+ grp.cacheOrGroupName() + ", " + "init=" + topVer + " ,other=" + otherAssignments.topologyVersion() + ']');
return false;
}
Set<Integer> p0 = new HashSet<>();
Set<Integer> p1 = new HashSet<>();
// Not compatible if a supplier has left.
for (ClusterNode node : rebalancingParts.keySet()) {
if (!grp.cacheObjectContext().kernalContext().discovery().alive(node))
return false;
}
for (Set<Integer> partitions : rebalancingParts.values())
p0.addAll(partitions);
for (GridDhtPartitionDemandMessage message : otherAssignments.values()) {
p1.addAll(message.partitions().fullSet());
p1.addAll(message.partitions().historicalSet());
}
// Not compatible if not a subset.
if (!p0.containsAll(p1))
return false;
p1 = Stream.concat(grp.affinity().cachedAffinity(otherAssignments.topologyVersion())
.primaryPartitions(ctx.localNodeId()).stream(), grp.affinity()
.cachedAffinity(otherAssignments.topologyVersion()).backupPartitions(ctx.localNodeId()).stream())
.collect(Collectors.toSet());
NavigableSet<AffinityTopologyVersion> toCheck = grp.affinity().cachedVersions()
.headSet(otherAssignments.topologyVersion(), false);
if (!toCheck.contains(topVer)) {
log.warning("History is not enough for checking compatible last rebalance, new rebalance started " +
"[grp=" + grp.cacheOrGroupName() + ", lastTop=" + topVer + ']');
return false;
}
for (AffinityTopologyVersion previousTopVer : toCheck.descendingSet()) {
if (previousTopVer.before(topVer))
break;
if (!ctx.exchange().lastAffinityChangedTopologyVersion(previousTopVer).equals(previousTopVer))
continue;
p0 = Stream.concat(grp.affinity().cachedAffinity(previousTopVer).primaryPartitions(ctx.localNodeId()).stream(),
grp.affinity().cachedAffinity(previousTopVer).backupPartitions(ctx.localNodeId()).stream())
.collect(Collectors.toSet());
// Not compatible if owners are different.
if (!p0.equals(p1))
return false;
}
return true;
}