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

The following examples show how to use java.util.TreeMap#subMap() . 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 j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Tests entrySet().contains() method behaviour with respect to entries
 * with null values.
 * Regression test for HARMONY-5788.
 */
public void test_entrySet_contains() throws Exception {
    TreeMap master = new TreeMap<String, String>();
    TreeMap test_map = new TreeMap<String, String>();

    master.put("null", null);
    Object[] entry = master.entrySet().toArray();
    assertFalse("Empty map should not contain the null-valued entry",
            test_map.entrySet().contains(entry[0]));

    Map<String, String> submap = test_map.subMap("a", "z");
    entry = master.entrySet().toArray();
    assertFalse("Empty submap should not contain the null-valued entry",
            submap.entrySet().contains(entry[0]));

    test_map.put("null", null);
    assertTrue("entrySet().containsAll(...) should work with null values",
            test_map.entrySet().containsAll(master.entrySet()));

    master.clear();
    master.put("null", '0');
    entry = master.entrySet().toArray();
    assertFalse("Null-valued entry should not equal non-null-valued entry",
            test_map.entrySet().contains(entry[0]));
}
 
Example 2
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 3
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * Test that the entrySet() method of a sub map produces correctly mutable
 * entries that propagate changes to the original map.
 */
public void testSubMapEntrySetSetValue() {
    TreeMap<String, String> map = new TreeMap<String, String>();
    map.put("A", "a");
    map.put("B", "b");
    map.put("C", "c");
    map.put("D", "d");
    NavigableMap<String, String> subMap = map.subMap("A", true, "C", true);

    Iterator<Entry<String, String>> iterator = subMap.entrySet().iterator();
    Entry<String, String> entryA = iterator.next();
    assertEquals("a", entryA.setValue("x"));
    assertEquals("x", entryA.getValue());
    assertEquals("x", subMap.get("A"));
    assertEquals("x", map.get("A"));
    Entry<String, String> entryB = iterator.next();
    assertEquals("b", entryB.setValue("y"));
    Entry<String, String> entryC = iterator.next();
    assertEquals("c", entryC.setValue("z"));
    assertEquals("y", entryB.getValue());
    assertEquals("y", subMap.get("B"));
    assertEquals("y", map.get("B"));
    assertEquals("z", entryC.getValue());
    assertEquals("z", subMap.get("C"));
    assertEquals("z", map.get("C"));
}
 
Example 4
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void test_subMap_NullTolerableComparator() {
    // Null Tolerable Comparator
    TreeMap<String, String> treeMapWithNull = new TreeMap<String, String>(
            new MockComparatorNullTolerable());
    treeMapWithNull.put("key1", "value1"); //$NON-NLS-1$ //$NON-NLS-2$
    treeMapWithNull.put(null, "value2"); //$NON-NLS-1$
    SortedMap<String, String> subMapWithNull = treeMapWithNull.subMap(null,
            true, "key1", true); //$NON-NLS-1$

    // RI fails here
    assertEquals("Size of subMap should be 2:", 2, subMapWithNull.size()); //$NON-NLS-1$
    assertEquals("value1", subMapWithNull.get("key1"));
    assertEquals("value2", subMapWithNull.get(null));
    treeMapWithNull.put("key0", "value2");
    treeMapWithNull.put("key3", "value3");
    treeMapWithNull.put("key4", "value4");
    treeMapWithNull.put("key5", "value5");
    treeMapWithNull.put("key6", "value6");
    assertEquals("Size of subMap should be 3:", 3, subMapWithNull.size()); //$NON-NLS-1$
    subMapWithNull = treeMapWithNull.subMap(null, false, "key1", true); //$NON-NLS-1$
    assertEquals("Size of subMap should be 2:", 2, subMapWithNull.size()); //$NON-NLS-1$
}
 
Example 5
Source File: TreeSubMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a new map from Integers 1-5 to Strings "A"-"E".
 */
private static NavigableMap map5() {
    TreeMap map = new TreeMap();
    assertTrue(map.isEmpty());
    map.put(zero, "Z");
    map.put(one, "A");
    map.put(five, "E");
    map.put(three, "C");
    map.put(two, "B");
    map.put(four, "D");
    map.put(seven, "F");
    assertFalse(map.isEmpty());
    assertEquals(7, map.size());
    return map.subMap(one, true, seven, false);
}
 
Example 6
Source File: TreeMapExample.java    From JavaTutorial with MIT License 5 votes vote down vote up
public void getRangeMap(TreeMap<String, String> maps, String firstKey, String lastKey) {
    SortedMap<String,String> subMaps =  maps.subMap(firstKey, lastKey);
    Iterator iterator = subMaps.entrySet().iterator();
    System.out.println("子Map如下");
    while (iterator.hasNext()) {
        Map.Entry<String, String> entry = (Map.Entry<String, String>) iterator.next();
        System.out.print("key = " + entry.getKey());
        System.out.println(" value = " + entry.getValue());
    }
}
 
Example 7
Source File: BinarySearchIndexTest.java    From chipster with MIT License 5 votes vote down vote up
private static void testLineIdentifiers(Index index, long startPosition) throws IOException,
		GBrowserException {
	
	//Line identifier must be same regardless of the line position in the request region 
	
	//First line of request region
	Region region;
	region = new Region(startPosition, startPosition + 100, new Chromosome("chr1"));
	TreeMap<IndexKey, String> lineMap = index.getFileLines(region);
	IndexKey id1 = lineMap.firstKey();
	
	//Last line  of request region
	region = new Region(startPosition - 100, startPosition + 1, new Chromosome("chr1"));
	lineMap = index.getFileLines(region);
	IndexKey id2 = lineMap.lastKey();
	
	//In the middle of request region
	region = new Region(startPosition - 100, startPosition + 100, new Chromosome("chr1"));
	lineMap = index.getFileLines(region);
	IndexKey fromKey = new IndexKey(new BpCoord(startPosition, new Chromosome("chr1")), 0);
	IndexKey toKey = new IndexKey(new BpCoord(startPosition, new Chromosome("chr1")), Long.MAX_VALUE);
	SortedMap<IndexKey, String> subMap = lineMap.subMap(fromKey, toKey);		
	IndexKey id3 = subMap.firstKey();
	
	Assert.assertEquals(id1, id2);
	Assert.assertEquals(id2, id3);
}
 
Example 8
Source File: TreeMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public void testSubMapContents2() {
    TreeMap map = map5();
    NavigableMap sm = map.subMap(two, true, three, false);
    assertEquals(1, sm.size());
    assertEquals(two, sm.firstKey());
    assertEquals(two, sm.lastKey());
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertFalse(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    assertFalse(i.hasNext());
    Iterator r = sm.descendingKeySet().iterator();
    k = (Integer)(r.next());
    assertEquals(two, k);
    assertFalse(r.hasNext());

    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(two));
    assertEquals(4, map.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertSame(sm.remove(three), null);
    assertEquals(4, map.size());
}
 
Example 9
Source File: ChrPosTreeMap.java    From systemsgenetics with GNU General Public License v3.0 5 votes vote down vote up
public NavigableMap<Integer,E> getChrRange(String chr, Integer fromKey, boolean fromInclusive, Integer toKey, boolean toInclusive){
	
	TreeMap<Integer, E> chrElements = data.get(chr);
	if(chrElements == null){
		return Collections.emptyNavigableMap();
	} else {
		return chrElements.subMap(fromKey, fromInclusive, toKey, toInclusive);
	}
	
}
 
Example 10
Source File: TreeMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * subMap returns map with keys in requested range
 */
public void testSubMapContents() {
    TreeMap map = map5();
    NavigableMap sm = map.subMap(two, true, four, false);
    assertEquals(two, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals(2, sm.size());
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertTrue(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    assertFalse(i.hasNext());
    Iterator r = sm.descendingKeySet().iterator();
    k = (Integer)(r.next());
    assertEquals(three, k);
    k = (Integer)(r.next());
    assertEquals(two, k);
    assertFalse(r.hasNext());

    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(two));
    assertEquals(4, map.size());
    assertEquals(1, sm.size());
    assertEquals(three, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals("C", sm.remove(three));
    assertTrue(sm.isEmpty());
    assertEquals(3, map.size());
}
 
Example 11
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testSubMapSerialization() {
    // Updated golden value since we have a different serialVersionUID in OpenJDK.
    String s = "aced0005737200216a6176612e7574696c2e547265654d617024417363656e646"
            + "96e675375624d61700cab946d1f0fab1c020000787200216a6176612e7574696c2"
            + "e547265654d6170244e6176696761626c655375624d617026617d4eacdd5933020"
            + "0075a000966726f6d53746172745a000b6869496e636c75736976655a000b6c6f4"
            + "96e636c75736976655a0005746f456e644c000268697400124c6a6176612f6c616"
            + "e672f4f626a6563743b4c00026c6f71007e00024c00016d7400134c6a6176612f7"
            + "574696c2f547265654d61703b7870000001007400016374000161737200116a617"
            + "6612e7574696c2e547265654d61700cc1f63e2d256ae60300014c000a636f6d706"
            + "17261746f727400164c6a6176612f7574696c2f436f6d70617261746f723b78707"
            + "372002a6a6176612e6c616e672e537472696e672443617365496e73656e7369746"
            + "97665436f6d70617261746f7277035c7d5c50e5ce0200007870770400000004710"
            + "07e000671007e00067400016271007e000c71007e000571007e000574000164710"
            + "07e000d78";
    TreeMap<String, String> map = new TreeMap<String, String>(
            String.CASE_INSENSITIVE_ORDER);
    map.put("a", "a");
    map.put("b", "b");
    map.put("c", "c");
    map.put("d", "d");
    SortedMap<String, String> subMap = map.subMap("a", "c");
    new SerializationTester<SortedMap<String, String>>(subMap, s) {
        @Override protected void verify(SortedMap<String, String> deserialized) {
            try {
                deserialized.put("e", "e");
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }
    }.test();
}
 
Example 12
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testNavigableSubMapSerialization() {
    // Updated golden value since we have a different serialVersionUID in OpenJDK.
    String s = "aced0005737200216a6176612e7574696c2e547265654d617024417363656e646"
            + "96e675375624d61700cab946d1f0fab1c020000787200216a6176612e7574696c2"
            + "e547265654d6170244e6176696761626c655375624d617026617d4eacdd5933020"
            + "0075a000966726f6d53746172745a000b6869496e636c75736976655a000b6c6f4"
            + "96e636c75736976655a0005746f456e644c000268697400124c6a6176612f6c616"
            + "e672f4f626a6563743b4c00026c6f71007e00024c00016d7400134c6a6176612f7"
            + "574696c2f547265654d61703b7870000100007400016374000161737200116a617"
            + "6612e7574696c2e547265654d61700cc1f63e2d256ae60300014c000a636f6d706"
            + "17261746f727400164c6a6176612f7574696c2f436f6d70617261746f723b78707"
            + "372002a6a6176612e6c616e672e537472696e672443617365496e73656e7369746"
            + "97665436f6d70617261746f7277035c7d5c50e5ce0200007870770400000004710"
            + "07e000671007e00067400016271007e000c71007e000571007e000574000164710"
            + "07e000d78";
    TreeMap<String, String> map = new TreeMap<String, String>(
            String.CASE_INSENSITIVE_ORDER);
    map.put("a", "a");
    map.put("b", "b");
    map.put("c", "c");
    map.put("d", "d");
    SortedMap<String, String> subMap = map.subMap("a", false, "c", true);
    new SerializationTester<SortedMap<String, String>>(subMap, s) {
        @Override protected void verify(SortedMap<String, String> deserialized) {
            try {
                deserialized.put("e", "e");
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }
    }.test();
}
 
Example 13
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * On JDK5, this fails with a NullPointerException after deserialization!
 */
public void testJava5SubMapSerialization() {
    String s = "aced0005737200186a6176612e7574696c2e547265654d6170245375624d6170"
            + "a5818343a213c27f0200055a000966726f6d53746172745a0005746f456e644c0"
            + "00766726f6d4b65797400124c6a6176612f6c616e672f4f626a6563743b4c0006"
            + "7468697324307400134c6a6176612f7574696c2f547265654d61703b4c0005746"
            + "f4b657971007e00017870000074000161737200116a6176612e7574696c2e5472"
            + "65654d61700cc1f63e2d256ae60300014c000a636f6d70617261746f727400164"
            + "c6a6176612f7574696c2f436f6d70617261746f723b78707372002a6a6176612e"
            + "6c616e672e537472696e672443617365496e73656e736974697665436f6d70617"
            + "261746f7277035c7d5c50e5ce020000787077040000000471007e000471007e00"
            + "047400016271007e000a7400016371007e000b7400016471007e000c7871007e0"
            + "00b";
    TreeMap<String, String> map = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
    map.put("a", "a");
    map.put("b", "b");
    map.put("c", "c");
    map.put("d", "d");
    SortedMap<String, String> subMap = map.subMap("a", "c");
    new SerializationTester<SortedMap<String, String>>(subMap, s) {
        @Override protected void verify(SortedMap<String, String> deserialized) {
            try {
                deserialized.put("e", "e");
                fail();
            } catch (IllegalArgumentException expected) {
            }
        }
    }.test();
}
 
Example 14
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * subMap returns map with keys in requested range
 */
public void testSubMapContents() {
    TreeMap map = map5();
    NavigableMap sm = map.subMap(two, true, four, false);
    assertEquals(two, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals(2, sm.size());
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertTrue(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    k = (Integer)(i.next());
    assertEquals(three, k);
    assertFalse(i.hasNext());
    Iterator r = sm.descendingKeySet().iterator();
    k = (Integer)(r.next());
    assertEquals(three, k);
    k = (Integer)(r.next());
    assertEquals(two, k);
    assertFalse(r.hasNext());

    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(two));
    assertEquals(4, map.size());
    assertEquals(1, sm.size());
    assertEquals(three, sm.firstKey());
    assertEquals(three, sm.lastKey());
    assertEquals("C", sm.remove(three));
    assertTrue(sm.isEmpty());
    assertEquals(3, map.size());
}
 
Example 15
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void testSubMapContents2() {
    TreeMap map = map5();
    NavigableMap sm = map.subMap(two, true, three, false);
    assertEquals(1, sm.size());
    assertEquals(two, sm.firstKey());
    assertEquals(two, sm.lastKey());
    assertFalse(sm.containsKey(one));
    assertTrue(sm.containsKey(two));
    assertFalse(sm.containsKey(three));
    assertFalse(sm.containsKey(four));
    assertFalse(sm.containsKey(five));
    Iterator i = sm.keySet().iterator();
    Object k;
    k = (Integer)(i.next());
    assertEquals(two, k);
    assertFalse(i.hasNext());
    Iterator r = sm.descendingKeySet().iterator();
    k = (Integer)(r.next());
    assertEquals(two, k);
    assertFalse(r.hasNext());

    Iterator j = sm.keySet().iterator();
    j.next();
    j.remove();
    assertFalse(map.containsKey(two));
    assertEquals(4, map.size());
    assertEquals(0, sm.size());
    assertTrue(sm.isEmpty());
    assertSame(sm.remove(three), null);
    assertEquals(4, map.size());
}
 
Example 16
Source File: TreeSubMapTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a new map from Integers 1-5 to Strings "A"-"E".
 */
private static NavigableMap map5() {
    TreeMap map = new TreeMap();
    assertTrue(map.isEmpty());
    map.put(zero, "Z");
    map.put(one, "A");
    map.put(five, "E");
    map.put(three, "C");
    map.put(two, "B");
    map.put(four, "D");
    map.put(seven, "F");
    assertFalse(map.isEmpty());
    assertEquals(7, map.size());
    return map.subMap(one, true, seven, false);
}
 
Example 17
Source File: PrefixMappedItemCache.java    From hadoop-connectors with Apache License 2.0 5 votes vote down vote up
/**
 * Helper function that handles creating the lower and upper bounds for calling {@link
 * SortedMap#subMap(Object, Object)}.
 *
 * @see SortedMap#subMap(Object, Object)
 */
private static <E> SortedMap<PrefixKey, E> getPrefixSubMap(
    TreeMap<PrefixKey, E> map, PrefixKey lowerBound) {
  PrefixKey upperBound =
      new PrefixKey(lowerBound.getBucket(), lowerBound.getObjectName() + Character.MAX_VALUE);
  return map.subMap(lowerBound, upperBound);
}
 
Example 18
Source File: BuildGlobalHiveDictTotalBuildMapper.java    From kylin with Apache License 2.0 4 votes vote down vote up
@Override
protected void doSetup(Context context) throws IOException, InterruptedException {
    Configuration conf = context.getConfiguration();
    mos = new MultipleOutputs(context);

    KylinConfig config;
    try {
        config = AbstractHadoopJob.loadKylinPropsAndMetadata();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    cols = config.getMrHiveDictColumnsExcludeRefColumns();


    String statPath = conf.get("partition.statistics.path");

    // get the input file name ,the file name format by colIndex-part-partitionNum, eg: 1-part-000019
    FileSplit fileSplit = (FileSplit) context.getInputSplit();
    String[] arr = fileSplit.getPath().getName().split("-");
    int partitionNum = Integer.parseInt(arr[2]);
    colIndex = Integer.parseInt(arr[0]);
    colName = cols[colIndex];
    logger.info("Input fileName:{}, colIndex:{}, colName:{}, partitionNum:{}", fileSplit.getPath().getName(), colIndex, colName, partitionNum);

    //last max dic value per column
    String lastMaxValuePath = conf.get("last.max.dic.value.path");
    logger.info("last.max.dic.value.path:" + lastMaxValuePath);
    long lastMaxDictValue = this.getLastMaxDicValue(conf, lastMaxValuePath);
    logger.info("last.max.dic.value.path:" + lastMaxValuePath + ",value=" + lastMaxDictValue);

    // Calculate the starting position of this file, the starting position of this file = sum (count) of all previous numbers + last max dic value of the column
    Map<Integer, TreeMap<Integer, Long>> allStats = getPartitionsCount(conf, statPath); //<colIndex,<reduceNum,count>>
    TreeMap<Integer, Long> partitionStats = allStats.get(colIndex);
    if (partitionNum != 0) {
        SortedMap<Integer, Long> subStat = partitionStats.subMap(0, true, partitionNum, false);
        subStat.forEach((k, v) -> {
            logger.info("Split num:{} and it's count:{}", k, v);
            start += v;
        });
    }
    start += lastMaxDictValue;
    logger.info("global dic.{}.split.num.{} build dict start offset is {}", colName, partitionNum, start);
}
 
Example 19
Source File: TreeMapTest.java    From j2objc with Apache License 2.0 4 votes vote down vote up
/**
 * java.util.TreeMap#subMap(java.lang.Object, java.lang.Object)
 */
public void test_subMapLjava_lang_ObjectLjava_lang_Object() {
    // Test for method java.util.SortedMap
    // java.util.TreeMap.subMap(java.lang.Object, java.lang.Object)
    SortedMap subMap = tm.subMap(objArray[100].toString(), objArray[109]
            .toString());
    assertEquals("subMap is of incorrect size", 9, subMap.size());
    for (int counter = 100; counter < 109; counter++) {
        assertTrue("SubMap contains incorrect elements", subMap.get(
                objArray[counter].toString()).equals(objArray[counter]));
    }

    try {
        tm.subMap(objArray[9].toString(), objArray[1].toString());
        fail("end key less than start key should throw IllegalArgumentException");
    } catch (IllegalArgumentException e) {
        // Expected
    }

    // Regression for Harmony-1161
    TreeMap<String, String> treeMapWithNull = new TreeMap<String, String>(
            new MockComparatorNullTolerable());
    treeMapWithNull.put("key1", "value1"); //$NON-NLS-1$ //$NON-NLS-2$
    treeMapWithNull.put(null, "value2"); //$NON-NLS-1$
    SortedMap<String, String> subMapWithNull = treeMapWithNull.subMap(null,
            "key1"); //$NON-NLS-1$
    assertEquals("Size of subMap should be 1:", 1, subMapWithNull.size()); //$NON-NLS-1$

    // Regression test for typo in lastKey method
    SortedMap<String, String> map = new TreeMap<String, String>();
    map.put("1", "one"); //$NON-NLS-1$ //$NON-NLS-2$
    map.put("2", "two"); //$NON-NLS-1$ //$NON-NLS-2$
    map.put("3", "three"); //$NON-NLS-1$ //$NON-NLS-2$
    assertEquals("3", map.lastKey());
    SortedMap<String, String> sub = map.subMap("1", "3"); //$NON-NLS-1$ //$NON-NLS-2$
    assertEquals("2", sub.lastKey()); //$NON-NLS-1$

    // NOTE: The contract of this method allows us to throw either
    // an NPE or a class cast exception.
    TreeMap t = new TreeMap();
    try {
        t.subMap(null, new Object());
        fail("Should throw a ClassCastException");
    } catch (ClassCastException cce) {
        // expected
    } catch (NullPointerException npe) {
        // expected
    }
}
 
Example 20
Source File: RafsRepStrategy.java    From Panako with GNU Affero General Public License v3.0 4 votes vote down vote up
public void queryForMonitor(TreeMap<Float,BitSet> fingerprints, TreeMap<Float,int[]> fingerprintProbabilities, int maxNumberOfResults,Set<Integer> avoid, QueryResultHandler handler) {
	

	int identifier = -1;
	int bestOffset = -1;
	int score = -1;
	int uncertainBitsToFlip=Config.getInt(Key.RAFS_BITS_TO_FLIP);
	int hammingDistanceThreshold = Config.getInt(Key.RAFS_HAMMING_DISTANCE_THRESHOLD);
	int timeOutInMilliseconds = Config.getInt(Key.RAFS_TIMEOUT);
	long start = System.currentTimeMillis();
	
	float startAt = fftDuration * 256 - fftDuration/2.0f;
	
	outerloop:
	for(Entry<Float,BitSet> entry : fingerprints.subMap(startAt, 10000000f).entrySet()){
		
		HashSet<Integer> keySet = new HashSet<>();
		int originalKey =  bitSetToInt(entry.getValue()); 
		keySet.add(originalKey);
		int[] probabilities = fingerprintProbabilities.get(entry.getKey());
		modifyPrint(keySet,originalKey,probabilities,uncertainBitsToFlip);

		for(Integer key : keySet){
			long[] matches = lut.get(key);
			if(matches !=null){
				for(int i = 0 ; i < matches.length ; i++){
					long matchID = getIdentifier(matches[i]);
					if(avoid.contains((int)matchID)){
						continue;
					}
					int[] prints = printsPerSong.get((int) matchID);
					long matchOffset = getOffset(matches[i]);
					float fromKey = matchOffset/1000.0f - 0.5f;
					float toKey = matchOffset/1000.0f + 0.5f;
					int fromIndex = (int) (fromKey/fftDuration);
					int toIndex = (int) (toKey/fftDuration);
					int index = -1;
					for(int j = fromIndex ; j > 0 && j < toIndex  && j < prints.length; j++){
						if(prints[j]==key)
							index = j;
					}
					toKey = entry.getKey() + fftDuration/2.0f;
					fromKey = entry.getKey() - 256*fftDuration - fftDuration/2.0f;
					
					if(fromKey>0 && index-256>0){	
						SortedMap<Float,BitSet> queryPrints = fingerprints.subMap(fromKey,toKey);
						int frameCounter = 0;
						int hammingDistance = 0;
						for(int j = index-256; j < index;j++){
							float printKey = fromKey +  frameCounter * fftDuration;
							printKey = queryPrints.subMap(printKey,printKey+fftDuration).firstKey();
							hammingDistance += Hamming.d(prints[j-1], bitSetToInt(queryPrints.get(printKey)));
							if(hammingDistance>hammingDistanceThreshold){
								break;
							}
							frameCounter++;
						}
						if(hammingDistance < hammingDistanceThreshold){
							identifier = (int) matchID;
							bestOffset = Math.round(index * fftDuration * 1000 - entry.getKey() * 1000);
							score = hammingDistance;
							break outerloop;
						}
					}
				}
			}
		}
		
		//time out detected?
		if(System.currentTimeMillis() - start > timeOutInMilliseconds){
			break outerloop;
		}
	}
	System.err.println("Fingerprints length: " + fingerprints.size());
	if(bestOffset!=-1){
		long actualOffset =  bestOffset;
		String desc = audioNameStore.get((int) identifier);
		handler.handleQueryResult(new QueryResult(0, 0, desc, "" + actualOffset ,score, actualOffset, 1.0, 1.0));
	}else{
		handler.handleEmptyResult(new QueryResult(0, 0, "","", 0, 0, 0,0));
	}
}