Java Code Examples for java.util.TreeMap#lowerEntry()

The following examples show how to use java.util.TreeMap#lowerEntry() . 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: TreeMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * lowerEntry returns preceding entry.
 */
public void testLowerEntry() {
    TreeMap map = map5();
    Map.Entry e1 = map.lowerEntry(three);
    assertEquals(two, e1.getKey());

    Map.Entry e2 = map.lowerEntry(six);
    assertEquals(five, e2.getKey());

    Map.Entry e3 = map.lowerEntry(one);
    assertNull(e3);

    Map.Entry e4 = map.lowerEntry(zero);
    assertNull(e4);
}
 
Example 2
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * lowerEntry returns preceding entry.
 */
public void testLowerEntry() {
    TreeMap map = map5();
    Map.Entry e1 = map.lowerEntry(three);
    assertEquals(two, e1.getKey());

    Map.Entry e2 = map.lowerEntry(six);
    assertEquals(five, e2.getKey());

    Map.Entry e3 = map.lowerEntry(one);
    assertNull(e3);

    Map.Entry e4 = map.lowerEntry(zero);
    assertNull(e4);
}
 
Example 3
Source File: ContainsNumberWithinKDistance.java    From interview with Apache License 2.0 5 votes vote down vote up
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    if (nums.length == 0 || k == 0) {
        return false;
    }
    TreeMap<Integer, Integer> map = new TreeMap<>();
    for (int i = 0; i < nums.length; i++) {
        int lowerEntry = nums[i] - t - 1;
        int higherEntry = nums[i] + t + 1;
        Map.Entry<Integer, Integer> higher = map.lowerEntry(higherEntry);
        if (higher != null && higher.getKey() >= nums[i]) {
            return true;
        }
        Map.Entry<Integer, Integer> lower = map.higherEntry(lowerEntry);
        if (lower != null && lower.getKey() <= nums[i]) {
            return true;
        }
        if (map.size() == k) {
            map.compute(nums[i - k], (key, val) -> {
                if (val == 1) {
                    return null;
                } else {
                    return val - 1;
                }
            });
        }
        map.compute(nums[i], (key, val) -> {
            if (val == null) {
                return 1;
            } else {
                return val + 1;
            }
        });
    }
    return false;
}
 
Example 4
Source File: AnomalyDetectorProfileRunner.java    From anomaly-detection with Apache License 2.0 4 votes vote down vote up
/**
 * Precondition:
 * 1. Index are rotated with name pattern ".opendistro-anomaly-results-history-{now/d}-1" and now is using UTC.
 * 2. Latest entry with error is recorded within enabled and disabled time.  Note disabled time can be null.
 *
 * Error is populated if error of the latest anomaly result is not empty.
 *
 * Two optimization to avoid scanning all anomaly result indices to get a detector's most recent error
 *
 * First, when a detector is running, we only need to scan the current index, not all of the rolled over ones
 *  since we are interested in the latest error.
 * Second, when a detector is disabled, we only need to scan the latest anomaly result indices created before the
 *  detector's enable time.
 *
 * @param detectorId detector id
 * @param enabledTimeMillis the time when AD job is enabled in milliseconds
 * @param listener listener to process the returned error or exception
 */
private void profileError(
    String detectorId,
    long enabledTimeMillis,
    Instant disabledTime,
    MultiResponsesDelegateActionListener<DetectorProfile> listener
) {
    String[] latestIndex = null;

    long disabledTimeMillis = 0;
    if (disabledTime != null) {
        disabledTimeMillis = disabledTime.toEpochMilli();
    }
    if (enabledTimeMillis > disabledTimeMillis) {
        // detector is still running
        latestIndex = new String[1];
        latestIndex[0] = AnomalyResult.ANOMALY_RESULT_INDEX;
    } else {
        String[] concreteIndices = indexNameExpressionResolver
            .concreteIndexNames(
                clusterService.state(),
                IndicesOptions.lenientExpandOpen(),
                AnomalyDetectionIndices.ALL_AD_RESULTS_INDEX_PATTERN
            );

        // find the latest from result indices such as .opendistro-anomaly-results-history-2020.04.06-1 and
        // /.opendistro-anomaly-results-history-2020.04.07-000002
        long maxTimestamp = -1;
        TreeMap<Long, List<String>> candidateIndices = new TreeMap<>();
        for (String indexName : concreteIndices) {
            Matcher m = Pattern.compile("\\.opendistro-anomaly-results-history-(\\d{4})\\.(\\d{2})\\.(\\d{2})-\\d+").matcher(indexName);
            if (m.matches()) {
                int year = Integer.parseInt(m.group(1));
                int month = Integer.parseInt(m.group(2));
                int date = Integer.parseInt(m.group(3));
                // month starts with 0
                calendar.clear();
                calendar.set(year, month - 1, date);
                // 2020.05.08 is translated to 1588896000000
                long timestamp = calendar.getTimeInMillis();

                // a candidate index can be created before or after enabled time, but the index is definitely created before disabled
                // time
                if (timestamp <= disabledTimeMillis && maxTimestamp <= timestamp) {
                    maxTimestamp = timestamp;
                    // we can have two rotations on the same day and we don't know which one has our data, so we keep all
                    List<String> indexList = candidateIndices.computeIfAbsent(timestamp, k -> new ArrayList<String>());
                    indexList.add(indexName);
                }
            }
        }
        List<String> candidates = new ArrayList<String>();
        List<String> latestCandidate = candidateIndices.get(maxTimestamp);

        if (latestCandidate != null) {
            candidates.addAll(latestCandidate);
        }

        // look back one more index for an edge case:
        // Suppose detector interval is 1 minute. Detector last run is at 2020-05-07, 11:59:50 PM,
        // then AD result indices rolled over as .opendistro-anomaly-results-history-2020.05.07-001
        // Detector next run will be 2020-05-08, 00:00:50 AM. If a user stop the detector at
        // 2020-05-08 00:00:10 AM, detector will not have AD result on 2020-05-08.
        // We check AD result indices one day earlier to make sure we can always get AD result.
        Map.Entry<Long, List<String>> earlierCandidate = candidateIndices.lowerEntry(maxTimestamp);
        if (earlierCandidate != null) {
            candidates.addAll(earlierCandidate.getValue());
        }
        latestIndex = candidates.toArray(new String[0]);
    }

    if (latestIndex == null || latestIndex.length == 0) {
        // no result index found: can be due to anomaly result is not created yet or result indices for the detector have been deleted.
        listener.onResponse(new DetectorProfile());
        return;
    }
    SearchRequest searchLatestResult = createLatestAnomalyResultRequest(detectorId, enabledTimeMillis, disabledTimeMillis, latestIndex);
    client.search(searchLatestResult, onGetLatestAnomalyResult(listener, detectorId));
}
 
Example 5
Source File: TreeMapExample.java    From JavaTutorial with MIT License 4 votes vote down vote up
public void getLowestEntry(TreeMap<String, String> maps, String key) {
    Map.Entry<String,String> entry = maps.lowerEntry(key);
    System.out.println("前一个的Entry如下");
    System.out.print("key = " + entry.getKey());
    System.out.println(" value = " + entry.getValue());
}