下面列出了怎么用java.util.AbstractMap的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Submap version of ConcurrentSkipListMap.getNearEntry
*/
Map.Entry<K,V> getNearEntry(K key, int rel) {
Comparator<? super K> cmp = m.comparator;
if (isDescending) { // adjust relation for direction
if ((rel & LT) == 0)
rel |= LT;
else
rel &= ~LT;
}
if (tooLow(key, cmp))
return ((rel & LT) != 0) ? null : lowestEntry();
if (tooHigh(key, cmp))
return ((rel & LT) != 0) ? highestEntry() : null;
for (;;) {
Node<K,V> n = m.findNear(key, rel, cmp);
if (n == null || !inBounds(n.key, cmp))
return null;
K k = n.key;
V v = n.getValidValue();
if (v != null)
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
}
}
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
Comparator<? super K> cmp = comparator;
K f = fence;
Node<K,V> e = current;
current = null;
for (; e != null; e = e.next) {
K k; Object v;
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
break;
if ((v = e.value) != null && v != sentinel()) {
@SuppressWarnings("unchecked") V vv = (V)v;
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
}
}
}
/** Returns a map that is a view onto a collection of values, using the
* provided function to convert a value to a key.
*
* <p>Unlike
* {@link com.google.common.collect.Maps#uniqueIndex(Iterable, com.google.common.base.Function)},
* returns a view whose contents change as the collection of values changes.
*
* @param values Collection of values
* @param function Function to map value to key
* @param <K> Key type
* @param <V> Value type
* @return Map that is a view onto the values
*/
public static <K, V> Map<K, V> asIndexMapJ(
final Collection<V> values,
final Function<V, K> function) {
final Collection<Map.Entry<K, V>> entries =
Collections2.transform(values, v -> Pair.of(function.apply(v), v));
final Set<Map.Entry<K, V>> entrySet =
new AbstractSet<Map.Entry<K, V>>() {
public Iterator<Map.Entry<K, V>> iterator() {
return entries.iterator();
}
public int size() {
return entries.size();
}
};
return new AbstractMap<K, V>() {
public Set<Entry<K, V>> entrySet() {
return entrySet;
}
};
}
public Map.Entry<String, String> split(String s) {
int idx = s.indexOf(delimiter);
if (idx < 0) {
return new AbstractMap.SimpleEntry<String, String>(s, "");
}
int k = 1;
while (k < numKeys) {
idx = s.indexOf(delimiter,idx + 1);
if (idx < 0) break;
k ++;
}
return new AbstractMap.SimpleEntry<String, String>(
s.substring(0, idx),
s.substring(idx+1)
);
}
/**
* Returns a {@code Metric} collected from {@link io.dropwizard.metrics5.Meter}.
*
* @param dropwizardMetric the metric name.
* @param meter the meter object to collect
* @return a {@code Metric}.
*/
private Metric collectMeter(MetricName dropwizardMetric, Meter meter) {
String metricName = DropWizardUtils.generateFullMetricName(dropwizardMetric.getKey(), "meter");
String metricDescription =
DropWizardUtils.generateFullMetricDescription(dropwizardMetric.getKey(), meter);
final AbstractMap.SimpleImmutableEntry<List<LabelKey>, List<LabelValue>> labels =
DropWizardUtils.generateLabels(dropwizardMetric);
MetricDescriptor metricDescriptor =
MetricDescriptor.create(
metricName, metricDescription, DEFAULT_UNIT, Type.CUMULATIVE_INT64, labels.getKey());
TimeSeries timeSeries =
TimeSeries.createWithOnePoint(
labels.getValue(),
Point.create(Value.longValue(meter.getCount()), clock.now()),
cumulativeStartTimestamp);
return Metric.createWithOneTimeSeries(metricDescriptor, timeSeries);
}
/**
* Method to validate supplied scale input. It performs a check that new ranges are identical to sealed ranges.
*
* @param segmentsToSeal segments to seal
* @param newRanges new ranges to create
* @param currentEpoch current epoch record
* @return true if scale input is valid, false otherwise.
*/
public static boolean validateInputRange(final List<Long> segmentsToSeal,
final List<Map.Entry<Double, Double>> newRanges,
final EpochRecord currentEpoch) {
boolean newRangesCheck = newRanges.stream().noneMatch(x -> x.getKey() >= x.getValue() && x.getValue() > 0);
if (newRangesCheck) {
List<Map.Entry<Double, Double>> oldRanges = segmentsToSeal.stream()
.map(segmentId -> {
StreamSegmentRecord segment = currentEpoch.getSegment(segmentId);
if (segment != null) {
return new AbstractMap.SimpleEntry<>(segment.getKeyStart(), segment.getKeyEnd());
} else {
return null;
}
}).filter(Objects::nonNull)
.collect(Collectors.toList());
return reduce(oldRanges).equals(reduce(newRanges));
}
return false;
}
void performReadIndexChecks(Collection<OperationWithCompletion> operations, ReadIndex readIndex) throws Exception {
AbstractMap<Long, Integer> expectedLengths = getExpectedLengths(operations);
AbstractMap<Long, InputStream> expectedData = getExpectedContents(operations);
for (Map.Entry<Long, InputStream> e : expectedData.entrySet()) {
int expectedLength = expectedLengths.getOrDefault(e.getKey(), -1);
@Cleanup
ReadResult readResult = readIndex.read(e.getKey(), 0, expectedLength, TIMEOUT);
int readLength = 0;
while (readResult.hasNext()) {
BufferView entry = readResult.next().getContent().join();
int length = entry.getLength();
readLength += length;
int streamSegmentOffset = expectedLengths.getOrDefault(e.getKey(), 0);
expectedLengths.put(e.getKey(), streamSegmentOffset + length);
AssertExtensions.assertStreamEquals(String.format("Unexpected data returned from ReadIndex. StreamSegmentId = %d, Offset = %d.",
e.getKey(), streamSegmentOffset), e.getValue(), entry.getReader(), length);
}
Assert.assertEquals("Not enough bytes were read from the ReadIndex for StreamSegment " + e.getKey(), expectedLength, readLength);
}
}
@VisibleForTesting
protected Optional<Map.Entry<String, VersionUniverse>> getVersionUniverse(TargetNode<?> root) {
Optional<String> universeName = getVersionUniverseName(root);
if (!universeName.isPresent() && !universes.isEmpty()) {
return Optional.of(Iterables.get(universes.entrySet(), 0));
}
if (!universeName.isPresent()) {
return Optional.empty();
}
VersionUniverse universe = universes.get(universeName.get());
if (universe == null) {
throw new VerifyException(
String.format(
"%s: unknown version universe \"%s\"", root.getBuildTarget(), universeName.get()));
}
return Optional.of(new AbstractMap.SimpleEntry<>(universeName.get(), universe));
}
@Override
public void accept(T t) {
if (depth > MAX_RECURSION_DEPTH) {
try (TreeSpliterator<T, Entry<Integer, T>> spliterator = new Depth<>(t, mapper, depth)) {
do { // nothing
} while (spliterator.tryAdvance(action));
}
return;
}
action.accept(new AbstractMap.SimpleImmutableEntry<>(depth, t));
try (Stream<T> stream = mapper.apply(depth, t)) {
if (stream != null) {
depth++;
stream.spliterator().forEachRemaining(this);
depth--;
}
}
}
public static void runWithArguments(String function, List<Object> arguments, Object expected) {
Supplier<Stream<Map.Entry<String, Object>>> kvStream = () -> StreamSupport
.stream(new XRange(arguments.size()), false)
.map(i -> new AbstractMap.SimpleImmutableEntry<>("var" + i, arguments.get(i)));
String args = kvStream.get().map(kv -> kv.getKey()).collect(Collectors.joining(","));
Map<String, Object> variables = kvStream.get().collect(Collectors.toMap(kv -> kv.getKey(), kv -> kv.getValue()));
String stellarStatement = function + "(" + args + ")";
String reason = stellarStatement + " != " + expected + " with variables: " + variables;
if (expected instanceof Double) {
if(!(Math.abs((Double) expected - (Double) run(stellarStatement, variables)) < 1e-6)) {
throw new AssertionError(reason);
}
} else {
if(!expected.equals(run(stellarStatement, variables))) {
throw new AssertionError(reason);
}
}
}
@Test
public void should_correctly_count_the_elements_of_a_sized_stream() {
// Given
List<Map.Entry<Integer, String>> entries = Arrays.asList(
new AbstractMap.SimpleEntry<>(1, "1"),
new AbstractMap.SimpleEntry<>(2, "2"),
new AbstractMap.SimpleEntry<>(3, "3"),
new AbstractMap.SimpleEntry<>(4, "4")
);
Stream<Map.Entry<Integer, String>> accumulatingStream = StreamsUtils.accumulateEntries(entries.stream(), String::concat);
// When
long count = accumulatingStream.count();
// Then
assertThat(count).isEqualTo(4);
}
public void forEachRemaining(Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
Comparator<? super K> cmp = comparator;
K f = fence;
Node<K,V> e = current;
current = null;
for (; e != null; e = e.next) {
K k; Object v;
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0)
break;
if ((v = e.value) != null && v != e) {
@SuppressWarnings("unchecked") V vv = (V)v;
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
}
}
}
@Override
public PooledTransaction getPoolTx(AionAddress from, BigInteger txNonce) {
if (from == null || txNonce == null) {
LOG.error("TxPoolA0.getPoolTx null args");
return null;
}
sortTxn();
lock.readLock().lock();
try {
AbstractMap.SimpleEntry<ByteArrayWrapper, BigInteger> entry =
this.getAccView(from).getMap().get(txNonce);
return (entry == null ? null : this.getMainMap().get(entry.getKey()).getTx());
} finally {
lock.readLock().unlock();
}
}
protected List<AbstractMap.SimpleEntry<Type, SArray.Size>> getReturnsType() {
Type[] returnTypes = extractReturnTypesFromElement();
List<AbstractMap.SimpleEntry<Type, SArray.Size>> ret = new ArrayList<>();
ReturnParameters annotations = method.getAnnotation(ReturnParameters.class);
SArray.Size[] arraySizeAnnotations =
annotations == null ? new SArray.Size[]{} : annotations.value();
for (int i = 0; i < returnTypes.length; i++) {
SArray.Size size = null;
if (arraySizeAnnotations.length > i) {
size = arraySizeAnnotations[i];
if (size.value().length == 0) {
size = null;
}
}
ret.add(new AbstractMap.SimpleEntry<>(returnTypes[i], size));
}
return ret;
}
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
Comparator<? super K> cmp = comparator;
K f = fence;
Node<K,V> e = current;
for (; e != null; e = e.next) {
K k; Object v;
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
e = null;
break;
}
if ((v = e.value) != null && v != e) {
current = e.next;
@SuppressWarnings("unchecked") V vv = (V)v;
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
return true;
}
}
current = e;
return false;
}
private static @NonNull Map<String, Object> computeAttributeMap(StructDefinition streamPacketContextDef) {
Builder<String, Object> attributeBuilder = ImmutableMap.<String, Object> builder();
for (String field : streamPacketContextDef.getDeclaration().getFieldsList()) {
IDefinition id = streamPacketContextDef.lookupDefinition(field);
if (id instanceof IntegerDefinition) {
attributeBuilder.put(field, ((IntegerDefinition) id).getValue());
} else if (id instanceof FloatDefinition) {
attributeBuilder.put(field, ((FloatDefinition) id).getValue());
} else if (id instanceof EnumDefinition) {
final EnumDefinition enumDec = (EnumDefinition) id;
attributeBuilder.put(field, new AbstractMap.SimpleImmutableEntry<>(
NonNullUtils.checkNotNull(enumDec.getStringValue()),
NonNullUtils.checkNotNull(enumDec.getIntegerValue())));
} else if (id instanceof StringDefinition) {
attributeBuilder.put(field, ((StringDefinition) id).getValue());
}
}
return attributeBuilder.build();
}
/**
* @return Map.Entry<QueryResult, Common.Status>
*/
@Override
public QueryResult next() throws LedgerException {
Map.Entry<QueryResult, Common.Status> map;
QueryResult result;
try {
result = commonIterator.next();
} catch (LedgerException e) {
log.error(e.getMessage(), e);
map = new AbstractMap.SimpleEntry<>(null, Common.Status.SERVICE_UNAVAILABLE);
return new QueryResult(map);
}
map = new AbstractMap.SimpleEntry<>(result
, result == null ? Common.Status.SERVICE_UNAVAILABLE : Common.Status.SUCCESS);
return new QueryResult(map);
}
/**
* Removes first entry; returns its snapshot.
* @return null if empty, else snapshot of first entry
*/
private Map.Entry<K,V> doRemoveFirstEntry() {
for (Node<K,V> b, n;;) {
if ((n = (b = head.node).next) == null)
return null;
Node<K,V> f = n.next;
if (n != b.next)
continue;
Object v = n.value;
if (v == null) {
n.helpDelete(b, f);
continue;
}
if (!n.casValue(v, null))
continue;
if (!n.appendMarker(f) || !b.casNext(n, f))
findFirst(); // retry
clearIndexToFirst();
@SuppressWarnings("unchecked") V vv = (V)v;
return new AbstractMap.SimpleImmutableEntry<K,V>(n.key, vv);
}
}
public boolean tryAdvance(Consumer<? super Map.Entry<K,V>> action) {
if (action == null) throw new NullPointerException();
Comparator<? super K> cmp = comparator;
K f = fence;
Node<K,V> e = current;
for (; e != null; e = e.next) {
K k; Object v;
if ((k = e.key) != null && f != null && cpr(cmp, f, k) <= 0) {
e = null;
break;
}
if ((v = e.value) != null && v != e) {
current = e.next;
@SuppressWarnings("unchecked") V vv = (V)v;
action.accept
(new AbstractMap.SimpleImmutableEntry<K,V>(k, vv));
return true;
}
}
current = e;
return false;
}
/**
* Decodes an URL path to extract a name and a potential version.
* @param path an URL path
* @return a non-null map entry (key = name, value = version)
*/
public static Map.Entry<String,String> decodeIconUrl( String path ) {
if( path.startsWith( "/" ))
path = path.substring( 1 );
String name = null, version = null;
String[] parts = path.split( "/" );
switch( parts.length ) {
case 2:
name = parts[ 0 ];
break;
case 3:
name = parts[ 0 ];
version = parts[ 1 ];
break;
default:
break;
}
return new AbstractMap.SimpleEntry<>( name, version );
}
/**
* Submap version of ConcurrentSkipListMap.getNearEntry.
*/
Map.Entry<K,V> getNearEntry(K key, int rel) {
Comparator<? super K> cmp = m.comparator;
if (isDescending) { // adjust relation for direction
if ((rel & LT) == 0)
rel |= LT;
else
rel &= ~LT;
}
if (tooLow(key, cmp))
return ((rel & LT) != 0) ? null : lowestEntry();
if (tooHigh(key, cmp))
return ((rel & LT) != 0) ? highestEntry() : null;
for (;;) {
Node<K,V> n = m.findNear(key, rel, cmp);
if (n == null || !inBounds(n.key, cmp))
return null;
K k = n.key;
V v = n.getValidValue();
if (v != null)
return new AbstractMap.SimpleImmutableEntry<K,V>(k, v);
}
}
/**
* Reads events and puts them in a queue for later checking (potentially by another thread).
*/
private void readAndQueueEvents(EventStreamReader<String> reader, int eventsToWrite, Queue<Entry<Integer, PositionImpl>> readEventsPositions) {
int eventCount = 1;
for (int i = 0; i < eventsToWrite; i++) {
final EventRead<String> event = reader.readNextEvent(1000);
if (event.getEvent() != null && !event.isCheckpoint()) {
// The reader should own only 1 segment.
readEventsPositions.add(new AbstractMap.SimpleEntry<>(eventCount, (PositionImpl) event.getPosition()));
eventCount++;
}
}
}
private static Entry<String, String> parsePropertyLine(String propertyLine, int lineNumber) {
String[] pair = propertyLine.split("=", 2);
if (pair.length != 2) {
throw new IllegalArgumentException("Invalid property format: no '=' character is found on line " + lineNumber);
}
String propertyKey = pair[0].trim();
String propertyValue = pair[1].trim();
return new AbstractMap.SimpleImmutableEntry<String, String>(propertyKey, propertyValue);
}
@Override
public Set<Map.Entry<String, ConfigValue>> entrySet() {
// total bloat just to work around lack of type variance
HashSet<java.util.Map.Entry<String, ConfigValue>> entries = new HashSet<Map.Entry<String, ConfigValue>>();
for (Map.Entry<String, AbstractConfigValue> e : value.entrySet()) {
entries.add(new AbstractMap.SimpleImmutableEntry<String, ConfigValue>(
e.getKey(), e
.getValue()));
}
return entries;
}
public static Map.Entry<SchemaTableName, KafkaTopicDescription> loadTpchTopicDescription(JsonCodec<KafkaTopicDescription> topicDescriptionJsonCodec, String topicName, SchemaTableName schemaTableName)
throws IOException
{
KafkaTopicDescription tpchTemplate = topicDescriptionJsonCodec.fromJson(ByteStreams.toByteArray(TestUtils.class.getResourceAsStream(format("/tpch/%s.json", schemaTableName.getTableName()))));
return new AbstractMap.SimpleImmutableEntry<>(
schemaTableName,
new KafkaTopicDescription(schemaTableName.getTableName(), Optional.of(schemaTableName.getSchemaName()), topicName, tpchTemplate.getKey(), tpchTemplate.getMessage()));
}
default Map.Entry<String, Class<RecordedEvent>> getNameAndClass() {
ParameterizedType type = (ParameterizedType) TypeToken.of(this.getClass()).getSupertype(RollbackSpec.class).getType();
try {
Class<RecordedEvent> publishedEventClass = (Class<RecordedEvent>) Class.forName(type.getActualTypeArguments()[0].getTypeName());
return new AbstractMap.SimpleEntry<>(publishedEventClass.getSimpleName(), publishedEventClass);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
@Test
public void visitAnd_ExceededValueThresholdMarkerJexlNode_RangeIndexOnlyTest() throws Exception {
ASTJexlScript script = JexlASTHelper.parseJexlQuery("BAZ == 'woot' && ((ExceededValueThresholdMarkerJexlNode = true) && (FOO >= 'e' && FOO <= 'm'))");
Key hit = new Key("row", "dataType" + Constants.NULL + "123.345.456");
List<Map.Entry<Key,Value>> source = new ArrayList<>();
source.add(new AbstractMap.SimpleEntry(new Key("row", "fi" + Constants.NULL + "BAZ", "woot" + Constants.NULL + "dataType" + Constants.NULL
+ "123.345.456"), new Value()));
source.add(new AbstractMap.SimpleEntry(
new Key("row", "tf", "dataType" + Constants.NULL + "123.345.456" + Constants.NULL + "f" + Constants.NULL + "FOO"), new Value()));
Set<String> termFrequencyFields = new HashSet<>();
termFrequencyFields.add("FOO");
// must have doc to get tf field values are within the bounds
// aggregation fields are not set so no document is created
vistAnd_ExceededValueThesholdMarkerJexlNode_termFrequencyTest(script, hit, source, false, null, termFrequencyFields, Collections.EMPTY_SET,
termFrequencyFields);
List<String> expected = new ArrayList<>();
expected.add("f");
Map<String,List<String>> fooMap = new HashMap<>();
fooMap.put("FOO", expected);
// turn on aggregation and see the document
vistAnd_ExceededValueThesholdMarkerJexlNode_termFrequencyTest(script, hit, source, true, fooMap, true);
}
private Map.Entry<UK, UV> getUnexpiredAndUpdateOrCleanup(Map.Entry<UK, TtlValue<UV>> e) {
TtlValue<UV> unexpiredValue;
try {
unexpiredValue = getWrappedWithTtlCheckAndUpdate(
e::getValue,
v -> original.put(e.getKey(), v),
originalIterator::remove);
} catch (Exception ex) {
throw new FlinkRuntimeException(ex);
}
return unexpiredValue == null ? null : new AbstractMap.SimpleEntry<>(e.getKey(), unexpiredValue.getUserValue());
}
/**
* Creates and returns a new SimpleImmutableEntry holding current
* mapping if this node holds a valid value, else null.
* @return new entry or null
*/
AbstractMap.SimpleImmutableEntry<K,V> createSnapshot() {
Object v = value;
if (v == null || v == this || v == BASE_HEADER)
return null;
@SuppressWarnings("unchecked") V vv = (V)v;
return new AbstractMap.SimpleImmutableEntry<K,V>(key, vv);
}
/**
* getValue returns last setValue for SimpleEntry
*/
public void testSetValue1() {
Map.Entry e2 = new AbstractMap.SimpleEntry(k1, v1);
Map.Entry e = new AbstractMap.SimpleEntry(e2);
assertEquals(k1, e.getKey());
assertEquals(v1, e.getValue());
e.setValue(k2);
assertEquals(k2, e.getValue());
assertFalse(e2.equals(e));
}