Java Code Examples for java.util.NavigableMap#values()

The following examples show how to use java.util.NavigableMap#values() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CountRanges.java    From interview with Apache License 2.0 6 votes vote down vote up
public int countRangeSum(int[] nums, int lower, int upper) {
    TreeMap<Long, Integer> map = new TreeMap<>();
    Map<Long, Integer> countMap = new HashMap<>();
    long prefixSum[] = new long[nums.length + 1];
    map.put(0l, 1);
    countMap.put(0l, 1);
    int count = 0;
    for (int i = 0; i < nums.length; i++) {
        prefixSum[i+1] = prefixSum[i] + nums[i];
        NavigableMap<Long, Integer> rangeMap =  map.subMap(prefixSum[i+1] - upper, true, prefixSum[i+1] - lower, true);
        if (rangeMap.size() > 0) {
            for (int c : rangeMap.values()) {
                count += c;
            }
        }
        if (countMap.containsKey(prefixSum[i+1])) {
            countMap.put(prefixSum[i+1], countMap.get(prefixSum[i+1]) + 1);
        } else {
            countMap.put(prefixSum[i+1], 1);
        }

        map.put(prefixSum[i+1], countMap.get(prefixSum[i+1]));
    }
    return count;
}
 
Example 2
Source File: KafkaValueSerializer.java    From kareldb with Apache License 2.0 6 votes vote down vote up
private List<GenericRecord> toArray(NavigableMap<Long, VersionedValue> object) {
    List<GenericRecord> records = new ArrayList<>();
    Schema recordSchema = avroSchema.getElementType();
    for (VersionedValue versionedValue : object.values()) {
        Comparable[] value = versionedValue.getValue();
        GenericRecordBuilder builder = new GenericRecordBuilder(recordSchema);
        for (Ord<Field> field : Ord.zip(recordSchema.getFields())) {
            if (field.i == 0) {
                builder.set(field.e, versionedValue.getVersion());
            } else if (field.i == 1) {
                builder.set(field.e, versionedValue.getCommit());
            } else if (field.i == 2) {
                builder.set(field.e, versionedValue.isDeleted());
            } else {
                if (!versionedValue.isDeleted()) {
                    Object v = AvroSchema.toAvroValue(field.e.schema(), value[field.i - 3]);
                    if (v != null) {
                        builder.set(field.e, v);
                    }
                }
            }
        }
        records.add(builder.build());
    }
    return records;
}
 
Example 3
Source File: ManagedLedgerOfflineBacklog.java    From pulsar with Apache License 2.0 5 votes vote down vote up
public PersistentOfflineTopicStats estimateUnloadedTopicBacklog(ManagedLedgerFactoryImpl factory,
        TopicName topicName) throws Exception {
    String managedLedgerName = topicName.getPersistenceNamingEncoding();
    long numberOfEntries = 0;
    long totalSize = 0;
    final NavigableMap<Long, MLDataFormats.ManagedLedgerInfo.LedgerInfo> ledgers = new ConcurrentSkipListMap<>();
    final PersistentOfflineTopicStats offlineTopicStats = new PersistentOfflineTopicStats(managedLedgerName,
            brokerName);

    // calculate total managed ledger size and number of entries without loading the topic
    readLedgerMeta(factory, topicName, ledgers);
    for (MLDataFormats.ManagedLedgerInfo.LedgerInfo ls : ledgers.values()) {
        numberOfEntries += ls.getEntries();
        totalSize += ls.getSize();
        if (accurate) {
            offlineTopicStats.addLedgerDetails(ls.getEntries(), ls.getTimestamp(), ls.getSize(), ls.getLedgerId());
        }
    }
    offlineTopicStats.totalMessages = numberOfEntries;
    offlineTopicStats.storageSize = totalSize;
    if (log.isDebugEnabled()) {
        log.debug("[{}] Total number of entries - {} and size - {}", managedLedgerName, numberOfEntries, totalSize);
    }

    // calculate per cursor message backlog
    calculateCursorBacklogs(factory, topicName, ledgers, offlineTopicStats);
    offlineTopicStats.statGeneratedAt.setTime(System.currentTimeMillis());

    return offlineTopicStats;
}
 
Example 4
Source File: TreeSubMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Values.toArray contains all values
 */
public void testDescendingValuesToArray() {
    NavigableMap map = dmap5();
    Collection v = map.values();
    Object[] ar = v.toArray();
    ArrayList s = new ArrayList(Arrays.asList(ar));
    assertEquals(5, ar.length);
    assertTrue(s.contains("A"));
    assertTrue(s.contains("B"));
    assertTrue(s.contains("C"));
    assertTrue(s.contains("D"));
    assertTrue(s.contains("E"));
}
 
Example 5
Source File: TreeSubMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * values collection contains all values
 */
public void testDescendingValues() {
    NavigableMap map = dmap5();
    Collection s = map.values();
    assertEquals(5, s.size());
    assertTrue(s.contains("A"));
    assertTrue(s.contains("B"));
    assertTrue(s.contains("C"));
    assertTrue(s.contains("D"));
    assertTrue(s.contains("E"));
}
 
Example 6
Source File: TreeSubMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * values collection contains all values
 */
public void testValues() {
    NavigableMap map = map5();
    Collection s = map.values();
    assertEquals(5, s.size());
    assertTrue(s.contains("A"));
    assertTrue(s.contains("B"));
    assertTrue(s.contains("C"));
    assertTrue(s.contains("D"));
    assertTrue(s.contains("E"));
}
 
Example 7
Source File: InMemCubeBuilder.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void build(BlockingQueue<T> input, InputConverterUnit<T> inputConverterUnit, ICuboidWriter output)
        throws IOException {
    NavigableMap<Long, CuboidResult> result = build(
            RecordConsumeBlockingQueueController.getQueueController(inputConverterUnit, input));
    try {
        for (CuboidResult cuboidResult : result.values()) {
            outputCuboid(cuboidResult.cuboidId, cuboidResult.table, output);
            cuboidResult.table.close();
        }
    } finally {
        output.close();
    }
}
 
Example 8
Source File: InMemCubeBuilder2.java    From kylin with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void build(BlockingQueue<T> input, InputConverterUnit<T> inputConverterUnit, ICuboidWriter output)
        throws IOException {
    NavigableMap<Long, CuboidResult> result = buildAndCollect(
            RecordConsumeBlockingQueueController.getQueueController(inputConverterUnit, input), null);
    try {
        for (CuboidResult cuboidResult : result.values()) {
            outputCuboid(cuboidResult.cuboidId, cuboidResult.table, output);
            cuboidResult.table.close();
        }
    } finally {
        output.close();
    }
}
 
Example 9
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Values.toArray contains all values
 */
public void testDescendingValuesToArray() {
    NavigableMap map = dmap5();
    Collection v = map.values();
    Object[] ar = v.toArray();
    ArrayList s = new ArrayList(Arrays.asList(ar));
    assertEquals(5, ar.length);
    assertTrue(s.contains("A"));
    assertTrue(s.contains("B"));
    assertTrue(s.contains("C"));
    assertTrue(s.contains("D"));
    assertTrue(s.contains("E"));
}
 
Example 10
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * values collection contains all values
 */
public void testDescendingValues() {
    NavigableMap map = dmap5();
    Collection s = map.values();
    assertEquals(5, s.size());
    assertTrue(s.contains("A"));
    assertTrue(s.contains("B"));
    assertTrue(s.contains("C"));
    assertTrue(s.contains("D"));
    assertTrue(s.contains("E"));
}
 
Example 11
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * values collection contains all values
 */
public void testValues() {
    NavigableMap map = map5();
    Collection s = map.values();
    assertEquals(5, s.size());
    assertTrue(s.contains("A"));
    assertTrue(s.contains("B"));
    assertTrue(s.contains("C"));
    assertTrue(s.contains("D"));
    assertTrue(s.contains("E"));
}
 
Example 12
Source File: TopTenReducer.java    From MapReduce-Demo with MIT License 5 votes vote down vote up
public void cleanup(Context context) throws IOException, InterruptedException {
	//将TreeMap反序处理,降序输出top10
	NavigableMap<Integer, Text> reverMap = visittimesMap.descendingMap();	//获得TreeMap反序
	for (Text t : reverMap.values()) {
		context.write(NullWritable.get(), t);
	}
}
 
Example 13
Source File: StorageSupplier.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
public StorageSupplier(NavigableMap<Integer, File> navigableMap) {
    this.navigableMap = navigableMap;
    ordered = new ArrayList<>(navigableMap.values());
    List<Integer> list = navigableMap.keySet().stream().limit(2).collect(Collectors.toList());
    // typically the list == [10, 20] and therefore the 20 - 10 == 10
    intervalEstimate = 2 <= list.size() ? list.get(1) - list.get(0) : 10;
}
 
Example 14
Source File: RouteValidation.java    From amodeus with GNU General Public License v2.0 5 votes vote down vote up
/** @param robotaxisWithMenu
 * @param avRequest
 * @param now
 * @param timeDb
 * @param requestMaintainer
 * @param roboTaxiMaintainer
 * @return The Closest RoboTaxi with a Shared Menu associated with it. */
/* package */ Optional<Entry<RoboTaxi, List<SharedCourse>>> getClosestValidSharingRoboTaxi(Set<RoboTaxi> robotaxisWithMenu, PassengerRequest avRequest, double now, //
        CachedNetworkTimeDistance timeDb, RequestHandler requestMaintainer, RoboTaxiHandler roboTaxiMaintainer) {

    GlobalAssert.that(robotaxisWithMenu.stream().allMatch(SharedCourseAccess::hasStarter));

    NavigableMap<Double, RoboTaxi> roboTaxisWithinMaxPickup = RoboTaxiUtilsFagnant.getRoboTaxisWithinMaxTime(avRequest.getFromLink(), //
            robotaxisWithMenu, timeDb, maxPickupTime, roboTaxiMaintainer, now);

    AvRouteHandler avRouteHandler = new AvRouteHandler();
    SharedCourse pickupCourse = SharedCourse.pickupCourse(avRequest);
    SharedCourse dropoffCourse = SharedCourse.dropoffCourse(avRequest);
    Map<RoboTaxi, SharedAvRoute> oldRoutes = new HashMap<>();

    // Calculate all routes and times
    for (RoboTaxi roboTaxi : roboTaxisWithinMaxPickup.values()) {
        List<SharedCourse> currentMenu = roboTaxi.getUnmodifiableViewOfCourses();
        for (int i = 0; i < currentMenu.size(); i++) {
            for (int j = i + 1; j < currentMenu.size() + 1; j++) {
                GlobalAssert.that(i < j);
                List<SharedCourse> newMenu = new ArrayList<>(currentMenu);
                newMenu.add(i, pickupCourse);
                newMenu.add(j, dropoffCourse);
                SharedAvRoute sharedAvRoute = SharedAvRoute.of(newMenu, roboTaxi.getDivertableLocation(), now, pickupDuration, dropoffDuration, timeDb);
                avRouteHandler.add(roboTaxi, sharedAvRoute);
            }
        }
        oldRoutes.put(roboTaxi, SharedAvRoute.of(roboTaxi.getUnmodifiableViewOfCourses(), roboTaxi.getDivertableLocation(), now, pickupDuration, dropoffDuration, timeDb));
    }
    Optional<Entry<RoboTaxi, List<SharedCourse>>> rt = getFastestValidEntry(avRouteHandler, avRequest, oldRoutes, now, requestMaintainer);
    rt.ifPresent(rtle -> GlobalAssert.that(Compatibility.of(rtle.getValue()).forCapacity(rtle.getKey().getCapacity())));
    return rt;
}
 
Example 15
Source File: InMemCubeBuilder.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void build(BlockingQueue<T> input, InputConverterUnit<T> inputConverterUnit, ICuboidWriter output)
        throws IOException {
    NavigableMap<Long, CuboidResult> result = build(
            RecordConsumeBlockingQueueController.getQueueController(inputConverterUnit, input));
    try {
        for (CuboidResult cuboidResult : result.values()) {
            outputCuboid(cuboidResult.cuboidId, cuboidResult.table, output);
            cuboidResult.table.close();
        }
    } finally {
        output.close();
    }
}
 
Example 16
Source File: InMemCubeBuilder2.java    From kylin-on-parquet-v2 with Apache License 2.0 5 votes vote down vote up
@Override
public <T> void build(BlockingQueue<T> input, InputConverterUnit<T> inputConverterUnit, ICuboidWriter output)
        throws IOException {
    NavigableMap<Long, CuboidResult> result = buildAndCollect(
            RecordConsumeBlockingQueueController.getQueueController(inputConverterUnit, input), null);
    try {
        for (CuboidResult cuboidResult : result.values()) {
            outputCuboid(cuboidResult.cuboidId, cuboidResult.table, output);
            cuboidResult.table.close();
        }
    } finally {
        output.close();
    }
}
 
Example 17
Source File: RegionRouteTable.java    From sofa-jraft with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the list of regions covered by startKey and endKey.
 */
public List<Region> findRegionsByKeyRange(final byte[] startKey, final byte[] endKey) {
    final StampedLock stampedLock = this.stampedLock;
    final long stamp = stampedLock.readLock();
    try {
        final byte[] realStartKey = BytesUtil.nullToEmpty(startKey);
        final NavigableMap<byte[], Long> subRegionMap;
        if (endKey == null) {
            subRegionMap = this.rangeTable.tailMap(realStartKey, false);
        } else {
            subRegionMap = this.rangeTable.subMap(realStartKey, false, endKey, true);
        }
        final List<Region> regionList = Lists.newArrayListWithCapacity(subRegionMap.size() + 1);
        final Map.Entry<byte[], Long> headEntry = this.rangeTable.floorEntry(realStartKey);
        if (headEntry == null) {
            reportFail(startKey);
            throw reject(startKey, "fail to find region by startKey");
        }
        regionList.add(safeCopy(this.regionTable.get(headEntry.getValue())));
        for (final Long regionId : subRegionMap.values()) {
            regionList.add(safeCopy(this.regionTable.get(regionId)));
        }
        return regionList;
    } finally {
        stampedLock.unlockRead(stamp);
    }
}
 
Example 18
Source File: SolrRegionObserver.java    From SolrCoprocessor with Apache License 2.0 4 votes vote down vote up
@Override
public void postPut(ObserverContext<RegionCoprocessorEnvironment> e, Put put, WALEdit edit, Durability durability)
    throws IOException {
	String tableName = e.getEnvironment().getRegion().getRegionInfo().getTable().getNameAsString();
	if (tableName.startsWith("hbase:")) { //Ԫ���ݱ�,����!
		return;
	}
	String rowKey = Bytes.toString(put.getRow());

	String cFamily = null;
	String cQualifier = null;
	String cValue = null;
	NavigableMap<byte[], List<Cell>> map = put.getFamilyCellMap();
	JsonObject jsonSet = new JsonObject();
	for (List<Cell> cells : map.values()) {
		for (Cell cell : cells) {
			cFamily = new String(CellUtil.cloneFamily(cell));
			cQualifier = new String(CellUtil.cloneQualifier(cell));
			cValue = new String(CellUtil.cloneValue(cell), SolrTools.UTF_8);
			if (cQualifier.endsWith("_s")) { //string
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", cValue));
			} else if (cQualifier.endsWith("_t")) { //text_general
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", cValue));
			} else if (cQualifier.endsWith("_dt")) { //date
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", cValue));
			} else if (cQualifier.endsWith("_i")) { //int
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putNumber("set", Integer.valueOf(cValue)));
			} else if (cQualifier.endsWith("_l")) { //long
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putNumber("set", Long.valueOf(cValue)));
			} else if (cQualifier.endsWith("_f")) { //float
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putNumber("set", Float.valueOf(cValue)));
			} else if (cQualifier.endsWith("_d")) { //double
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putNumber("set", Double.valueOf(cValue)));
			} else if (cQualifier.endsWith("_b")) { //boolean
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putBoolean("set", Boolean.valueOf(cValue)));
			} else { //������Ҫ������,����!
				continue;
			}
		}
	}
	if (jsonSet.size() == 0) { //˵��û��solr��ѯ�ֶ�
		return;
	}

	jsonSet.putString(F_ID, tableName + F_SEPARATOR + rowKey);
	jsonSet.putObject(F_TABLENAME, (new JsonObject()).putString("set", tableName));
	jsonSet.putObject(F_ROWKEY, (new JsonObject()).putString("set", rowKey));
	jsonSet.putObject(F_UPDATETIME, (new JsonObject()).putString("set", SolrTools.solrDateFormat.format(new java.util.Date())));

	log.debug("postPut!!! " + jsonSet.encode());
	_bqUpdate.enqueue(jsonSet.encode().getBytes(SolrTools.UTF_8));
}
 
Example 19
Source File: SolrRegionObserver.java    From SolrCoprocessor with Apache License 2.0 4 votes vote down vote up
@Override
public void postDelete(ObserverContext<RegionCoprocessorEnvironment> e, Delete delete, WALEdit edit,
    Durability durability) throws IOException {
	String tableName = e.getEnvironment().getRegion().getRegionInfo().getTable().getNameAsString();
	if (tableName.startsWith("hbase:")) { //Ԫ���ݱ�,����!
		return;
	}
	String rowKey = new String(delete.getRow());

	String cFamily = null;
	String cQualifier = null;
	NavigableMap<byte[], List<Cell>> map = delete.getFamilyCellMap();
	JsonObject jsonSet = new JsonObject();
	for (List<Cell> cells : map.values()) {
		for (Cell cell : cells) {
			cFamily = new String(CellUtil.cloneFamily(cell));
			cQualifier = new String(CellUtil.cloneQualifier(cell));
			if (cQualifier.endsWith("_s")) { //string
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else if (cQualifier.endsWith("_t")) { //text_general
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else if (cQualifier.endsWith("_dt")) { //date
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else if (cQualifier.endsWith("_i")) { //int
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else if (cQualifier.endsWith("_l")) { //long
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else if (cQualifier.endsWith("_f")) { //float
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else if (cQualifier.endsWith("_d")) { //double
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else if (cQualifier.endsWith("_b")) { //boolean
				jsonSet.putObject(cFamily + F_SEPARATOR + cQualifier, (new JsonObject()).putString("set", null));
			} else { //������Ҫ������,����!
				continue;
			}
		}
	}
	if (jsonSet.size() == 0) { //˵��û��solr�ֶ�
		if (delete.numFamilies() == e.getEnvironment().getRegion().getTableDesc().getFamilies().size()) { //˵����ɾ����
			JsonObject jsonDel = new JsonObject();
			jsonDel.putObject("delete", (new JsonObject()).putString("query", F_ID + ":\"" + tableName + F_SEPARATOR + rowKey + "\""));

			log.debug("postDelete!!! Row:" + jsonDel.encode());

			_bqDelete.enqueue(jsonDel.encode().getBytes(SolrTools.UTF_8));
		} else { //˵������ɾ����
			return;
		}
	} else {
		jsonSet.putString(F_ID, tableName + F_SEPARATOR + rowKey);
		jsonSet.putObject(F_UPDATETIME, (new JsonObject()).putString("set", SolrTools.solrDateFormat.format(new java.util.Date())));

		log.debug("postDelete!!! Column:" + jsonSet.encode());
		_bqUpdate.enqueue(jsonSet.encode().getBytes(SolrTools.UTF_8));
	}
}
 
Example 20
Source File: CollectionsTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
public void test_synchronizedNavigableMap_values() {
    NavigableMap<String, Integer> map = synchronizedNavigableMap(
            new TreeMap<>(createMap("key3", 3, "key1", 1, "key4", 4, "key2", 2)));
    Collection<Integer> values = map.values();
    check_orderedCollection(values, Arrays.asList(1, 2, 3, 4));
}