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

The following examples show how to use java.util.TreeMap#lastKey() . 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: TreeMapAPITest.java    From openjdk-systemtest with Apache License 2.0 6 votes vote down vote up
public void testLastKey()
{
	// create two random treemaps and retrieve their last keys
	TreeMap<Integer,Integer> tree1 = TreeMapFactory.getTree(TreeMapFactory.SIZE/2);
	Comparable<Integer> lastkey1 = (Comparable<Integer>)tree1.lastKey();
	
	TreeMap<Integer,Integer> tree2 = TreeMapFactory.getTree(TreeMapFactory.SIZE/2);
	Comparable<Integer> lastkey2 = (Comparable<Integer>)tree2.lastKey();
	
	// join them together and check the last key is correct
	tree1.putAll(tree2);
	
	if (lastkey1.compareTo((Integer)lastkey2) >= 0)
	{
		assertEquals(lastkey1, tree1.lastKey());
	}
	else
	{
		assertEquals(lastkey2, tree1.lastKey());
	}
	
	// put the largest Integer in and see if it's the last key
	tree1.put(new Integer(Integer.MAX_VALUE), null);
	assertEquals(new Integer(Integer.MAX_VALUE), tree1.lastKey());
}
 
Example 2
Source File: ModeCalculator.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Override
public Double apply(double[] x) {
  ArgChecker.notNull(x, "x");
  ArgChecker.isTrue(x.length > 0, "x cannot be empty");
  if (x.length == 1) {
    return x[0];
  }
  double[] x1 = Arrays.copyOf(x, x.length);
  Arrays.sort(x1);
  TreeMap<Integer, Double> counts = new TreeMap<>();
  int count = 1;
  for (int i = 1; i < x1.length; i++) {
    if (Math.abs(x1[i] - x1[i - 1]) < EPS) {
      count++;
    } else {
      counts.put(count, x1[i - 1]);
      count = 1;
    }
  }
  if (counts.lastKey() == 1) {
    throw new MathException("Could not find mode for array; no repeated values");
  }
  return counts.lastEntry().getValue();
}
 
Example 3
Source File: UMLModelDiff.java    From RefactoringMiner with MIT License 6 votes vote down vote up
private void processCandidates(List<MoveAttributeRefactoring> candidates, List<MoveAttributeRefactoring> refactorings) {
 if(candidates.size() > 1) {
  TreeMap<Integer, List<MoveAttributeRefactoring>> map = new TreeMap<Integer, List<MoveAttributeRefactoring>>();
  for(MoveAttributeRefactoring candidate : candidates) {
   int compatibility = computeCompatibility(candidate);
   if(map.containsKey(compatibility)) {
	   map.get(compatibility).add(candidate);
   }
   else {
	   List<MoveAttributeRefactoring> refs = new ArrayList<MoveAttributeRefactoring>();
	   refs.add(candidate);
	   map.put(compatibility, refs);
   }
  }
  int maxCompatibility = map.lastKey();
  refactorings.addAll(map.get(maxCompatibility));
 }
 else if(candidates.size() == 1) {
  refactorings.addAll(candidates);
 }
}
 
Example 4
Source File: Renderer.java    From gpx-animator with Apache License 2.0 6 votes vote down vote up
private void mergeConnectedSpans(final List<Long[]> spanList, final TreeMap<Long, Point2D> timePointMap) {
    long t0 = timePointMap.firstKey();
    long t1 = timePointMap.lastKey() + cfg.getTailDuration();

    for (final Iterator<Long[]> iter = spanList.iterator(); iter.hasNext();) {
        final Long[] span = iter.next();
        if (t0 > span[0] && t1 < span[1]) {
            // swallowed
            return;
        }

        if (t0 < span[0] && t1 > span[1]) {
            // swallows
            iter.remove();
        } else if (t1 > span[0] && t1 < span[1]) {
            t1 = span[1];
            iter.remove();
        } else if (t0 < span[1] && t0 > span[0]) {
            t0 = span[0];
            iter.remove();
        }
    }

    spanList.add(new Long[]{t0, t1});
}
 
Example 5
Source File: NGramCorrelationForm.java    From Ngram-Graphs with Apache License 2.0 6 votes vote down vote up
private Integer[] splitPointsByDelimiterList(String sStr, SortedMap lDelimiters) {
    ArrayList alRes = new ArrayList();
    TreeMap lLocal = new TreeMap();
    lLocal.putAll(lDelimiters);
    
    // For every candidate delimiter
    while (lLocal.size() > 0) {
        Object oNext = lLocal.lastKey();
        // Get all split points
        int iNextSplit = 0;
        int iLastSplit = 0;
        while ((iNextSplit = sStr.indexOf((String)lDelimiters.get(oNext), iLastSplit)) > -1)
        {
            // TODO : Check
            alRes.add(new Integer(iNextSplit + ((String)lDelimiters.get(oNext)).length()));
            iLastSplit = iNextSplit + 1;
        }
        
        lLocal.remove(oNext);
    }
    Integer [] iaRes = new Integer[alRes.size()];
    alRes.toArray(iaRes);
    gr.demokritos.iit.jinsect.utils.bubbleSortArray(iaRes);
    
    return iaRes;
}
 
Example 6
Source File: EntropyChunker.java    From Ngram-Graphs with Apache License 2.0 6 votes vote down vote up
protected Integer[] splitPointsByDelimiterList(String sStr, SortedMap lDelimiters) {
    ArrayList alRes = new ArrayList();
    TreeMap lLocal = new TreeMap();
    lLocal.putAll(lDelimiters);
    
    // For every candidate delimiter
    while (lLocal.size() > 0) {
        Object oNext = lLocal.lastKey();
        // Get all split points
        int iNextSplit = 0;
        int iLastSplit = 0;
        while ((iNextSplit = sStr.indexOf((String)lDelimiters.get(oNext), iLastSplit)) > -1) {
            // TODO : Check
            alRes.add(new Integer(iNextSplit + ((String)lDelimiters.get(oNext)).length()));
            iLastSplit = iNextSplit + 1;
        }
        
        lLocal.remove(oNext);
    }
    Integer [] iaRes = new Integer[alRes.size()];
    alRes.toArray(iaRes);
    gr.demokritos.iit.jinsect.utils.bubbleSortArray(iaRes);
    
    return iaRes;
}
 
Example 7
Source File: 10132 File Fragmentation.java    From UVA with GNU General Public License v3.0 5 votes vote down vote up
public static void main (String [] args) throws Exception {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	int testCaseCount=Integer.parseInt(br.readLine());
	br.readLine(); //empty line
	for (int testCase=0;testCase<testCaseCount;testCase++) {
		TreeMap<Integer,HashMap<String,Integer>> map=new TreeMap<>();
		String s;
		int sCount=0;
		while (true) {
			s=br.readLine();
			if (s!=null && s.length()>0) {
				addToMap(map,s);
				sCount++;
			} else {
				break;
			}
		}
		
		int minLength=map.firstKey();
		int maxLength=map.lastKey();
		TreeSet<String> possibleSol=new TreeSet<>();
		for (String s1 : map.get(minLength).keySet()) for (String s2 : map.get(maxLength).keySet()) {
			possibleSol.add(s1+s2);
			possibleSol.add(s2+s1);
		}
		
		boolean flag=false;
		for (String sol : possibleSol) {
			flag=solutionOK(sol,map,sCount/2);
			if (flag) {
				printSolution(testCase,sol);
				break;
			}
		}

		if (!flag) printSolution(testCase,possibleSol.iterator().next());
	}
}
 
Example 8
Source File: 11136 Hoax or What.java    From UVA with GNU General Public License v3.0 5 votes vote down vote up
public static void main (String [] args) throws IOException {
	BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
	String s;
	
	while (!(s=br.readLine()).equals("0")) {
		int N=Integer.parseInt(s);
		long cost=0; //wtf.
		TreeMap<Integer,Integer> map=new TreeMap<>();
		for (int i=0;i<N;i++) {
			StringTokenizer st=new StringTokenizer(br.readLine());
			int k=Integer.parseInt(st.nextToken());
			for (int i2=0;i2<k;i2++) {
				int num=Integer.parseInt(st.nextToken());
				map.put(num,map.getOrDefault(num,0)+1);
			}
			
			int highest=map.lastKey();
			if (map.get(highest)==1) map.remove(highest);
			else map.put(highest,map.get(highest)-1);
			
			int lowest=map.firstKey();
			if (map.get(lowest)==1) map.remove(lowest);
			else map.put(lowest,map.get(lowest)-1);
			
			cost+=(highest-lowest);
		}
		System.out.println(cost);
	}
}
 
Example 9
Source File: TreeMapDemo.java    From javacore with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) {
    TreeMap<Integer, String> treeMap = new TreeMap<>();
    for (int i = 0; i < chars.length; i++) {
        treeMap.put(i, chars[i]);
    }
    System.out.println(treeMap);
    Integer low = treeMap.firstKey();
    Integer high = treeMap.lastKey();
    System.out.println(low);
    System.out.println(high);
    Iterator<Integer> it = treeMap.keySet().iterator();
    for (int i = 0; i <= 6; i++) {
        if (i == 3) {
            low = it.next();
        }
        if (i == 6) {
            high = it.next();
        } else {
            it.next();
        }
    }
    System.out.println(low);
    System.out.println(high);
    System.out.println(treeMap.subMap(low, high));
    System.out.println(treeMap.headMap(high));
    System.out.println(treeMap.tailMap(low));
}
 
Example 10
Source File: TypeBindingInheritanceDetection.java    From JDeodorant with MIT License 5 votes vote down vote up
public Set<String> getLeavesInDeepestLevels() {
	Set<String> leavesInDeepestLevels = new LinkedHashSet<String>();
	for(InheritanceTree tree : inheritanceTreeList) {
		TreeMap<Integer, Set<String>> levelMap = tree.getLeavesByLevel();
		Integer lastLevel = levelMap.lastKey();
		if(lastLevel > 0) {
			leavesInDeepestLevels.addAll(levelMap.get(lastLevel));
		}
	}
	return leavesInDeepestLevels;
}
 
Example 11
Source File: MemoryBranch.java    From pumpernickel with MIT License 5 votes vote down vote up
@Override
public Revision getLastRevision(K beanId) {
	if (beanId == null)
		throw new NullPointerException();

	Object lock = acquireReadLock();
	try {
		Map<String, TreeMap<Revision, Object>> fieldData = dataByBeanId
				.get(beanId);
		Revision lastRevision = null;
		if (fieldData != null) {
			for (Entry<String, TreeMap<Revision, Object>> entry : fieldData
					.entrySet()) {
				TreeMap<Revision, Object> revisionValueMap = entry
						.getValue();
				Revision fieldLastRevision = revisionValueMap.lastKey();
				if (lastRevision == null
						|| fieldLastRevision.compareTo(lastRevision) > 0) {
					lastRevision = fieldLastRevision;
				}
			}
		}

		return lastRevision;
	} finally {
		releaseLock(lock);
	}
}
 
Example 12
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 13
Source File: LinkDocHandler.java    From io with Apache License 2.0 5 votes vote down vote up
/**
 * 検索結果からLinkDocHandlerを生成するコンストラクタ.
 * @param searchHit 検索結果データ
 */
public LinkDocHandler(final DcSearchHit searchHit) {
    this.id = searchHit.getId();

    Map<String, Object> source = searchHit.getSource();
    this.cellId = source.get(KEY_CELL_ID).toString();
    if (source.containsKey(KEY_BOX_ID) && source.get(KEY_BOX_ID) != null) {
        this.boxId = source.get(KEY_BOX_ID).toString();
    }
    if (source.containsKey(KEY_NODE_ID) && source.get(KEY_NODE_ID) != null) {
        this.nodeId = source.get(KEY_NODE_ID).toString();
    }

    // ES 保存時の一意キー作成
    String srcType = source.get(KEY_ENT1_TYPE).toString();
    String srcId = source.get(KEY_ENT1_ID).toString();
    String tgtType = source.get(KEY_ENT2_TYPE).toString();
    String tgtId = source.get(KEY_ENT2_ID).toString();
    TreeMap<String, String> tm = new TreeMap<String, String>();
    tm.put(srcType, srcId);
    tm.put(tgtType, tgtId);

    this.ent1Type = tm.firstKey();
    this.ent2Type = tm.lastKey();
    this.ent1Key = tm.get(ent1Type);
    this.ent2Key = tm.get(ent2Type);
    this.published = Long.parseLong(source.get(KEY_PUBLISHED).toString());
    this.updated = Long.parseLong(source.get(KEY_UPDATED).toString());
}
 
Example 14
Source File: UnencumberedLoadFacet.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the best Load value to avoid encumberance from Load for the
 * Player Character identified by the given CharID.
 * 
 * @param id
 *            The CharID identifying the Player Character
 * @return The best Load value to avoid encumberance from Load for the
 *         Player Character identified by the given CharID.
 */
public Load getBestLoad(CharID id)
{
	TreeMap<Load, Set<Object>> map = (TreeMap<Load, Set<Object>>) getCachedMap(id);
	if (map == null || map.isEmpty())
	{
		return Load.LIGHT;
	}
	return map.lastKey();
}
 
Example 15
Source File: UnencumberedArmorFacet.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the best Load value to avoid encumberance from Armor for the
 * Player Character identified by the given CharID.
 * 
 * @param id
 *            The CharID identifying the Player Character
 * @return The best Load value to avoid encumberance from Armor for the
 *         Player Character identified by the given CharID.
 */
public Load getBestLoad(CharID id)
{
	TreeMap<Load, Set<Object>> map = (TreeMap<Load, Set<Object>>) getCachedMap(id);
	if (map == null || map.isEmpty())
	{
		return Load.LIGHT;
	}
	return map.lastKey();
}
 
Example 16
Source File: UnencumberedLoadFacet.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the best Load value to avoid encumberance from Load for the
 * Player Character identified by the given CharID.
 * 
 * @param id
 *            The CharID identifying the Player Character
 * @return The best Load value to avoid encumberance from Load for the
 *         Player Character identified by the given CharID.
 */
public Load getBestLoad(CharID id)
{
	TreeMap<Load, Set<Object>> map = (TreeMap<Load, Set<Object>>) getCachedMap(id);
	if (map == null || map.isEmpty())
	{
		return Load.LIGHT;
	}
	return map.lastKey();
}
 
Example 17
Source File: UnencumberedArmorFacet.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
/**
 * Returns the best Load value to avoid encumberance from Armor for the
 * Player Character identified by the given CharID.
 * 
 * @param id
 *            The CharID identifying the Player Character
 * @return The best Load value to avoid encumberance from Armor for the
 *         Player Character identified by the given CharID.
 */
public Load getBestLoad(CharID id)
{
	TreeMap<Load, Set<Object>> map = (TreeMap<Load, Set<Object>>) getCachedMap(id);
	if (map == null || map.isEmpty())
	{
		return Load.LIGHT;
	}
	return map.lastKey();
}
 
Example 18
Source File: PhoenixHBaseAccessor.java    From ambari-metrics with Apache License 2.0 5 votes vote down vote up
private static TreeMap<Long, Double> readLastMetricValueFromJSON(String json) throws IOException {
  TreeMap<Long, Double> values = readMetricFromJSON(json);
  Long lastTimeStamp = values.lastKey();

  TreeMap<Long, Double> valueMap = new TreeMap<Long, Double>();
  valueMap.put(lastTimeStamp, values.get(lastTimeStamp));
  return valueMap;
}
 
Example 19
Source File: MemoryBranch.java    From pumpernickel with MIT License 4 votes vote down vote up
private void commitRevision(Revision r, Collection<K> ignorableBeans)
		throws DuplicateBeanIdException, MissingBeanException,
		SaveException {
	for (Entry<K, Map<String, TreeMap<Revision, Object>>> beanEntry : dataByBeanId
			.entrySet()) {
		K beanId = beanEntry.getKey();
		if (!ignorableBeans.contains(beanId)) {
			for (Entry<String, TreeMap<Revision, Object>> fieldRevisionEntry : beanEntry
					.getValue().entrySet()) {
				TreeMap<Revision, Object> revisionMap = fieldRevisionEntry
						.getValue();

				Object newValue = revisionMap.get(r);
				boolean isDefined = newValue != null;
				if (isDefined) {
					String fieldName = fieldRevisionEntry.getKey();

					Revision lastFieldRevision = revisionMap.lastKey();

					if (lastCommittedRevision != null
							&& lastFieldRevision != null
							&& lastFieldRevision
									.compareTo(lastCommittedRevision) < 0) {
						continue;
					}

					if (FIELD_CREATED.toString().equals(fieldName)) {
						parent.createBean(beanId);
					} else if (FIELD_DELETED.toString().equals(fieldName)) {
						parent.deleteBean(beanId);
					} else {
						if (newValue == NULL)
							newValue = null;
						try {
							Revision lastFieldParentRevision = parent
									.getLastRevision(beanId, fieldName);
							if (parentRevision != null
									&& lastFieldParentRevision != null
									&& parentRevision
											.compareTo(lastFieldParentRevision) < 0)
								throw new SaveException(parent, beanId,
										lastFieldParentRevision,
										"The field \""
												+ fieldName
												+ "\" on bean \""
												+ beanId
												+ "\" was modified after "
												+ parentRevision.toString()
														.toLowerCase());

							parent.setField(beanId, fieldName, newValue);
						} catch (SaveException e) {
							throw new SaveException(this, beanId, r,
									"The parent branch contained a conflicting value for field \""
											+ fieldName + "\" for bean \""
											+ beanId + "\".");
						}
					}
				}
			}
		}
	}
}
 
Example 20
Source File: MemoryBranch.java    From pumpernickel with MIT License 4 votes vote down vote up
@Override
public Map<String, Object> getBean(K beanId) {
	if (beanId == null)
		throw new NullPointerException();

	Object lock = acquireReadLock();
	try {
		Map<String, Object> returnValue;
		if (parent == null) {
			returnValue = null;
		} else {
			returnValue = parent.getBean(beanId);
		}

		Map<String, TreeMap<Revision, Object>> beanDataByField = dataByBeanId
				.get(beanId);

		if (beanDataByField == null) {
			return returnValue;
		}

		TreeMap<Revision, Object> deletionMap = beanDataByField
				.get(FIELD_DELETED.toString());
		TreeMap<Revision, Object> creationMap = beanDataByField
				.get(FIELD_CREATED.toString());
		Revision lastDeletion = deletionMap == null ? null : deletionMap
				.lastKey();
		Revision lastCreation = creationMap == null ? null : creationMap
				.lastKey();
		if (lastDeletion != null
				&& (lastCreation == null || lastCreation
						.compareTo(lastDeletion) < 0)) {
			return null;
		}

		if (lastCreation != null) {
			returnValue = new HashMap<>();
		}

		for (Entry<String, TreeMap<Revision, Object>> entry : beanDataByField
				.entrySet()) {
			String fieldName = entry.getKey();
			if (!(FIELD_DELETED.toString().equals(fieldName) || FIELD_CREATED
					.toString().equals(fieldName))) {
				Revision fieldRevision = entry.getValue().lastKey();
				if (lastCreation == null
						|| lastCreation.compareTo(fieldRevision) < 0) {
					if (returnValue == null)
						throw new IllegalStateException(
								"Bean data was detected for \""
										+ beanId
										+ "\" (field \""
										+ fieldName
										+ "\", but there is no record of that bean being created.");
					Object value = entry.getValue().lastEntry().getValue();
					if (value == NULL)
						value = null;
					returnValue.put(fieldName, value);
				}
			}
		}

		return returnValue;
	} finally {
		releaseLock(lock);
	}
}