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

The following examples show how to use java.util.TreeMap#containsKey() . 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: Solution.java    From java-technology-stack with MIT License 6 votes vote down vote up
public List<Integer> topKFrequent(int[] nums, int k) {

        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int num: nums){
            if(map.containsKey(num))
                map.put(num, map.get(num) + 1);
            else
                map.put(num, 1);
        }

        PriorityQueue<Freq> pq = new PriorityQueue<>();
        for(int key: map.keySet()){
            if(pq.size() < k)
                pq.add(new Freq(key, map.get(key)));
            else if(map.get(key) > pq.peek().freq){
                pq.remove();
                pq.add(new Freq(key, map.get(key)));
            }
        }

        LinkedList<Integer> res = new LinkedList<>();
        while(!pq.isEmpty())
            res.add(pq.remove().e);
        return res;
    }
 
Example 2
Source File: Solution.java    From java-technology-stack with MIT License 6 votes vote down vote up
public List<Integer> topKFrequent(int[] nums, int k) {

        TreeMap<Integer, Integer> map = new TreeMap<>();
        for(int num: nums){
            if(map.containsKey(num))
                map.put(num, map.get(num) + 1);
            else
                map.put(num, 1);
        }

        PriorityQueue<Freq> pq = new PriorityQueue<>();
        for(int key: map.keySet()){
            if(pq.getSize() < k)
                pq.enqueue(new Freq(key, map.get(key)));
            else if(map.get(key) > pq.getFront().freq){
                pq.dequeue();
                pq.enqueue(new Freq(key, map.get(key)));
            }
        }

        LinkedList<Integer> res = new LinkedList<>();
        while(!pq.isEmpty())
            res.add(pq.dequeue().e);
        return res;
    }
 
Example 3
Source File: FieldDescriptor.java    From android-test with Apache License 2.0 6 votes vote down vote up
static List<FieldDescriptor> getFieldDescriptorsFromAnnotation(
    Class<?> clazz, Class<RemoteMsgField> annotation) {
  TreeMap<Integer, FieldDescriptor> targetFields = new TreeMap<>();
  Field[] declaredFields = clazz.getDeclaredFields();
  for (Field field : declaredFields) {
    if (field.isAnnotationPresent(annotation)) {
      RemoteMsgField remoteMsgFieldAnnotation = field.getAnnotation(annotation);
      int order = remoteMsgFieldAnnotation.order();
      if (targetFields.containsKey(order)) {
        throw new IllegalStateException(
            String.format(
                Locale.ROOT, "Duplicate field order %s for field %s", order, field.getName()));
      }
      targetFields.put(order, of(field, remoteMsgFieldAnnotation));
    }
  }
  return ImmutableList.copyOf(targetFields.values());
}
 
Example 4
Source File: PropertyService.java    From cerberus-source with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Auxiliary method that returns the execution data for a property.
 *
 * @param hashTemp1 list of execution data
 * @param eachTccp property to be calculated
 * @param forceCalculation indicates whether a property must be
 * re-calculated if it was already computed in previous steps
 * @param tecd execution data for the property
 * @return the updated execution data for the property
 */
private TestCaseExecutionData getExecutionDataFromList(TreeMap<String, TestCaseExecutionData> hashTemp1, TestCaseCountryProperties eachTccp, boolean forceCalculation, TestCaseExecutionData tecd) {
    LOG.debug("Searching " + eachTccp.getProperty() + " Into list of " + hashTemp1.size());
    try {

        if (hashTemp1.containsKey(eachTccp.getProperty())) {
            if (forceCalculation) {
                LOG.debug("Property has already been calculated but forcing new calculation by removing it : " + hashTemp1.get(eachTccp.getProperty()));
                hashTemp1.remove(eachTccp.getProperty());
                return tecd;
            } else {
                LOG.debug("Property has already been calculated : " + hashTemp1.get(eachTccp.getProperty()));
                return hashTemp1.get(eachTccp.getProperty());
            }
        } else {
            LOG.debug("Property was never calculated.");
            return tecd;
        }

    } catch (Exception ex) {
        LOG.error("Exception catched inside getExecutionDataFromList : " + ex, ex);
    }
    return tecd;

}
 
Example 5
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 6
Source File: CoreNotebookService.java    From lams with GNU General Public License v2.0 6 votes vote down vote up
@Override
   public TreeMap<Long, List<NotebookEntry>> getEntriesGroupedByLesson(Integer userID) {
TreeMap<Long, List<NotebookEntry>> lessonIdToEntriesMap = new TreeMap<Long, List<NotebookEntry>>();
List<NotebookEntry> entries = getEntry(userID, CoreNotebookConstants.SCRATCH_PAD);

for (NotebookEntry entry : entries) {
    if (lessonIdToEntriesMap.containsKey(entry.getExternalID())) {
	String lessonName = lessonIdToEntriesMap.get(entry.getExternalID()).get(0).getLessonName();
	entry.setLessonName(lessonName);
	lessonIdToEntriesMap.get(entry.getExternalID()).add(entry);
	
    } else {
	Lesson lesson = (Lesson) baseDAO.find(Lesson.class, entry.getExternalID());
	List<NotebookEntry> newEntryList = new ArrayList<NotebookEntry>();

	entry.setLessonName(lesson.getLessonName());
	newEntryList.add(entry);

	lessonIdToEntriesMap.put(entry.getExternalID(), newEntryList);
    }
}

return lessonIdToEntriesMap;
   }
 
Example 7
Source File: MDAGNode.java    From MDAG with Apache License 2.0 6 votes vote down vote up
/**
 * Determines whether the sets of transition paths from two MDAGNodes are equivalent. This is an expensive operation.
 
 * @param outgoingTransitionTreeMap1        a TreeMap containing entries collectively representing
 *                                          all of a node's outgoing transitions
 * @param outgoingTransitionTreeMap2        a TreeMap containing entries collectively representing
 *                                          all of a node's outgoing transitions
 * @return                                  true if the set of transition paths from {@code node1}
 *                                          and {@code node2} are equivalent
 */
public static boolean haveSameTransitions(MDAGNode node1, MDAGNode node2)
{
    TreeMap<Character, MDAGNode> outgoingTransitionTreeMap1 = node1.outgoingTransitionTreeMap;
    TreeMap<Character, MDAGNode> outgoingTransitionTreeMap2 = node2.outgoingTransitionTreeMap;
    
    if(outgoingTransitionTreeMap1.size() == outgoingTransitionTreeMap2.size())
    {
        //For each transition in outgoingTransitionTreeMap1, get the identically lableed transition
        //in outgoingTransitionTreeMap2 (if present), and test the equality of the transitions' target nodes
        for(Entry<Character, MDAGNode> transitionKeyValuePair : outgoingTransitionTreeMap1.entrySet())
        {
            Character currentCharKey = transitionKeyValuePair.getKey();
            MDAGNode currentTargetNode = transitionKeyValuePair.getValue();
            
            if(!outgoingTransitionTreeMap2.containsKey(currentCharKey) || !outgoingTransitionTreeMap2.get(currentCharKey).equals(currentTargetNode))
                return false;
        }
        /////
    }
    else
        return false;
    
    return true;
}
 
Example 8
Source File: AbstractFloatDataType.java    From ghidra with Apache License 2.0 5 votes vote down vote up
/**
 * Returns all built-in float data-types
 * @param dtm optional program data-type manager, if specified
 * generic data-types will be returned in place of fixed-sized data-types.
 */
public static AbstractFloatDataType[] getFloatDataTypes(DataTypeManager dtm) {
	TreeMap<Integer, AbstractFloatDataType> floatMap = getFloatTypes();
	TreeMap<Integer, AbstractFloatDataType> newFloatMap = floatMap;
	if (dtm != null) {
		DataOrganization dataOrganization = dtm.getDataOrganization();
		if (dataOrganization != null) {
			newFloatMap = new TreeMap<Integer, AbstractFloatDataType>();
			newFloatMap.put(dataOrganization.getFloatSize(),
				(AbstractFloatDataType) FloatDataType.dataType.clone(dtm));
			if (!newFloatMap.containsKey(dataOrganization.getDoubleSize())) {
				newFloatMap.put(dataOrganization.getDoubleSize(),
					(AbstractFloatDataType) DoubleDataType.dataType.clone(dtm));
			}
			if (!newFloatMap.containsKey(dataOrganization.getLongDoubleSize())) {
				newFloatMap.put(dataOrganization.getLongDoubleSize(),
					(AbstractFloatDataType) LongDoubleDataType.dataType.clone(dtm));
			}
			for (int size : floatMap.keySet()) {
				if (!newFloatMap.containsKey(size)) {
					newFloatMap.put(size, (AbstractFloatDataType) floatMap.get(size).clone(dtm));
				}
			}
		}
	}
	AbstractFloatDataType[] floatTypeArray = new AbstractFloatDataType[newFloatMap.size()];
	newFloatMap.values().toArray(floatTypeArray);
	return floatTypeArray;
}
 
Example 9
Source File: PropertyContainer.java    From lams with GNU General Public License v2.0 5 votes vote down vote up
private void collectPersistentAttributesUsingClassLevelAccessType(
		TreeMap<String, XProperty> persistentAttributeMap,
		Map<String,XProperty> persistentAttributesFromGetters,
		List<XProperty> fields,
		List<XProperty> getters) {
	if ( classLevelAccessType == AccessType.FIELD ) {
		for ( XProperty field : fields ) {
			if ( persistentAttributeMap.containsKey( field.getName() ) ) {
				continue;
			}

			persistentAttributeMap.put( field.getName(), field );
		}
	}
	else {
		for ( XProperty getter : getters ) {
			final String name = getter.getName();

			// HHH-10242 detect registration of the same property getter twice - eg boolean isId() + UUID getId()
			final XProperty previous = persistentAttributesFromGetters.get( name );
			if ( previous != null ) {
				throw new org.hibernate.boot.MappingException(
						LOG.ambiguousPropertyMethods(
								xClass.getName(),
								HCANNHelper.annotatedElementSignature( previous ),
								HCANNHelper.annotatedElementSignature( getter )
						),
						new Origin( SourceType.ANNOTATION, xClass.getName() )
				);
			}

			if ( persistentAttributeMap.containsKey( name ) ) {
				continue;
			}

			persistentAttributeMap.put( getter.getName(), getter );
			persistentAttributesFromGetters.put( name, getter );
		}
	}
}
 
Example 10
Source File: GenomicBoundaries.java    From systemsgenetics with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Method to add a Genomic Boundary to the Genmoic Boundaries set.
 * @param chromosome
 * @param beginPoint
 * @param endPoint 
 */
public final void addBoundary(String chromosome, Integer beginPoint, int endPoint){
	
	chromosome = removeChr(chromosome);
	
	TreeMap<Integer, ArrayList<GenomicBoundary<V>>> chromosomeBoundaries;
	if(!genomicsBoundaries.containsKey(chromosome)){
		chromosomeBoundaries = new TreeMap<Integer, ArrayList<GenomicBoundary<V>>>();
		genomicsBoundaries.put(chromosome, chromosomeBoundaries);
	} else {
		chromosomeBoundaries = genomicsBoundaries.get(chromosome);
	}

	GenomicBoundary genomicBoundary;

	genomicBoundary = new GenomicBoundary(chromosome, beginPoint, endPoint);
	
	//Test if start point already contains boundary. If not so save new boundary. If start site contains 

	ArrayList<GenomicBoundary<V>> boundaries;
	if(chromosomeBoundaries.containsKey(beginPoint)){
		boundaries = chromosomeBoundaries.get(beginPoint);
	} else {
		boundaries = new ArrayList<GenomicBoundary<V>>();
		chromosomeBoundaries.put(beginPoint, boundaries);
	}
	boundaries.add(genomicBoundary);

	//chromosomeBoundaries.put(beginPoint, genomicBoundary);
	
	
	removedSubBoundaries = false;
	
}
 
Example 11
Source File: ExperimentingWithAlgorithms.java    From IngressAnimations with GNU General Public License v3.0 5 votes vote down vote up
private static void insert(TreeMap<Double, Integer> pdf, double rank) {
	if (pdf.containsKey(rank)) {
		pdf.put(rank, pdf.get(rank)+1);
	} else {
		pdf.put(rank, 1);
	}
}
 
Example 12
Source File: LocalDocReader.java    From TranskribusCore with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Check existence of PAGE XML or txt files and return tree map of (fake) image filenames and files
 * @param baseDir folder in which images should be found
 * @return
 * @throws IOException
 */
public static TreeMap<String, File> createDummyImgFiles(File baseDir) throws IOException {
	
	//for syncing page file: the base directory can also be directly the page folder		
	File xmlDir = (baseDir.getName().equals(LocalDocConst.PAGE_FILE_SUB_FOLDER)) ? baseDir : getPageXmlInputDir(baseDir);
	
	//File xmlDir = getPageXmlInputDir(baseDir);
	File txtDir = getTxtInputDir(baseDir);
	
	// check whether xml directory contains files, if not, assume txt directory has content
	File workingDir = (xmlDir==null || !xmlDir.exists())?txtDir:xmlDir;
	File[] fileArr = workingDir.listFiles();
	
	//Use number sensitive ordering so that:		
	//img1 -> img2 -> ... -> img9 -> img10 -> etc.
	//try Java 8: http://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html#naturalOrder--
	Comparator<String> naturalOrderComp = new NaturalOrderComparator();
	TreeMap<String, File> pageMap = new TreeMap<>(naturalOrderComp);

	if (fileArr == null || fileArr.length == 0){
		if (!workingDir.exists()) {
			logger.debug("Could not find directory " +workingDir.getName() + " holding files for synchronisation!");
		}

		logger.debug("Folder " + workingDir.getAbsolutePath() + " does not contain any files!");
		logger.debug("No PAGE XML nor txt files found - returning empty TreeMap");
		return pageMap;
	}
	
	for (File page : fileArr) {
		final String pageName = FilenameUtils.getBaseName(page.getName());
		if (!pageMap.containsKey(pageName)) {
			//new page. add this xml
			File img = new File(baseDir, pageName+".png");
			pageMap.put(pageName, img);
			logger.debug(pageName + ": created fake image " + img.getName());
		} 
	}
	return pageMap;
}
 
Example 13
Source File: 11057 Exact Sum.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));
	String s;
	while ((s=br.readLine())!=null) {
		int N=Integer.parseInt(s);
		TreeMap<Integer, Integer> map=new TreeMap<>();
		StringTokenizer st=new StringTokenizer(br.readLine());
		for (int n=0;n<N;n++) {
			int v=Integer.parseInt(st.nextToken());
			map.put(v, map.getOrDefault(v, 0)+1);
		}
		int sum=Integer.parseInt(br.readLine());
		
		PriorityQueue<Solution> q=new PriorityQueue<>();
		ArrayList<Integer> list=new ArrayList<>();
		list.addAll(map.keySet());
		for (int i=0;i<list.size();i++) {
			int p1=list.get(i);
			int p2=sum-p1;
			if ((p1==p2 && map.get(p1)>=2) || (p1!=p2 && map.containsKey(p2))) q.offer(new Solution(p1, p2));
		}
		
		Solution sol=q.poll();
		System.out.printf("Peter should buy books whose prices are %d and %d.\n\n", sol.small, sol.large);
		br.readLine();
	}
}
 
Example 14
Source File: HashTable.java    From java-technology-stack with MIT License 5 votes vote down vote up
public V remove(K key){
    V ret = null;
    TreeMap<K, V> map = hashtable[hash(key)];
    if(map.containsKey(key)){
        ret = map.remove(key);
        size --;

        if(size <= lowerTol * M && M > initCapacity)
            resize(M / 2);
    }
    return ret;
}
 
Example 15
Source File: HashTable.java    From java-technology-stack with MIT License 5 votes vote down vote up
public void set(K key, V value){
    TreeMap<K, V> map = hashtable[hash(key)];
    if(!map.containsKey(key))
        throw new IllegalArgumentException(key + " doesn't exist!");

    map.put(key, value);
}
 
Example 16
Source File: LocaleIDParser.java    From trekarta with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Returns a map of the keywords and values, or null if there are none.
 */
public Map<String, String> getKeywordMap() {
    if (keywords == null) {
        TreeMap<String, String> m = null;
        if (setToKeywordStart()) {
            // trim spaces and convert to lower case, both keywords and values.
            do {
                String key = getKeyword();
                if (key.length() == 0) {
                    break;
                }
                char c = next();
                if (c != KEYWORD_ASSIGN) {
                    // throw new IllegalArgumentException("key '" + key + "' missing a value.");
                    if (c == DONE) {
                        break;
                    } else {
                        continue;
                    }
                }
                String value = getValue();
                if (value.length() == 0) {
                    // throw new IllegalArgumentException("key '" + key + "' missing a value.");
                    continue;
                }
                if (m == null) {
                    m = new TreeMap<String, String>(getKeyComparator());
                } else if (m.containsKey(key)) {
                    // throw new IllegalArgumentException("key '" + key + "' already has a value.");
                    continue;
                }
                m.put(key, value);
            } while (next() == ITEM_SEPARATOR);
        }
        keywords = m != null ? m : Collections.<String, String>emptyMap();
    }

    return keywords;
}
 
Example 17
Source File: TreeMapTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * containsKey(null) of nonempty map throws NPE
 */
public void testContainsKey_NullPointerException() {
    TreeMap c = map5();
    try {
        c.containsKey(null);
        shouldThrow();
    } catch (NullPointerException success) {}
}
 
Example 18
Source File: LobstackDB.java    From jelectrum with MIT License 4 votes vote down vote up
public void run()
{ 
  TreeMap<String, Long> check_delay_map = new TreeMap<String, Long>();

  while(true)
  { 
    try
    { 
      boolean done_something = false;

      for(Lobstack ls : stack_list)
      { 
        String name = ls.getName();
        int depth=4;
        double target=0.50;
        long max_size = 1024L * 1024L * 1024L;
        if (jelly.getSpaceLimited())
        { 
          name = "limited-" + name;
          depth=16;
          target=0.95;
          max_size=4L * 1024L * 1024L * 1024L;
        }
        if ((!check_delay_map.containsKey(name)) || (check_delay_map.get(name) < System.currentTimeMillis()))
        { 
          if (ls.cleanup(depth, target, max_size, cleanup_log))
          { 
            done_something=true;
          }
          else
          { 
            check_delay_map.put(name, 60L * 60L * 1000L + System.currentTimeMillis());
          }

        }
      }
      if (!done_something)
      { 
        //cleanup_log.println("Sleeping");
        sleep(5L * 1000L);
      }
    }
    catch(Exception e)
    { 
      e.printStackTrace();
    }
  }
}
 
Example 19
Source File: TreeMapAPITest.java    From openjdk-systemtest with Apache License 2.0 4 votes vote down vote up
public void testContainsValue()
{
	TreeMap<Integer,String> tree = new TreeMap<Integer,String>();
	// look for a null value
	assertFalse("Looking for null value in an empty tree", tree.containsValue(null));
	// look for a non-null value
	assertFalse("Looking for non-null value in an empty tree", tree.containsValue(Integer.toString(10)));
	
	// put some values in the tree
	Random random = new Random(23412849);
	Integer k = null;
	for (int i=0; i<TreeMapFactory.SIZE; i++)
	{
		// find a key that isn't in the tree already
		do 
		{
			k = new Integer(random.nextInt());
		} while (tree.containsKey(k));
		// put a String value in the tree

		tree.put(k, Integer.toString(i));
		
	}
	
	// look for each string
	for (int i=0; i<TreeMapFactory.SIZE; i++)
	{
		assertTrue("Tree doesn't contain value " + i, tree.containsValue(Integer.toString(i)));
	}
	
	// look for one that shouldn't be there
	assertFalse("Tree contains value " + TreeMapFactory.SIZE, tree.containsValue(Integer.toString(TreeMapFactory.SIZE)));
	
	// look for a null key
	assertFalse("Looking for null value in tree that doesn't contain one", tree.containsValue(null));
	
	// put a null in the tree
	k = new Integer(random.nextInt());
	tree.put(k, null);
	assertTrue("Looking for null value in tree that contains one", tree.containsValue(null));
}
 
Example 20
Source File: reading.java    From systemsgenetics with GNU General Public License v3.0 4 votes vote down vote up
/**
 * Read SNP information files
 * @param annotationFileFolder
 * @param minMaf
 * @param firstRowAsHeader
 * @return 
 */
public static HashMap<String, TreeMap<Integer, String>> readMultipleSNPAnnotationFiles3(String annotationFileFolder, double minMaf, boolean firstRowAsHeader) {
    HashMap<String, TreeMap<Integer, String>> snpInfo = new HashMap<String, TreeMap<Integer, String>>(25);
    File file = new File(annotationFileFolder);
    File[] files = file.listFiles();
    ArrayList<File> vecFiles = new ArrayList<File>();
    for (int f = 0; f < files.length; f++) {
        if (files[f].getAbsolutePath().endsWith(".txt")) {
            vecFiles.add(files[f]);
        }
    }

    for (int f = 0; f < vecFiles.size(); f++) {
        File currentFile = vecFiles.get(f);
        System.out.println("Processing:\t" + f + "\t" + currentFile.getAbsolutePath());
        String currectChr = "";
        TreeMap<Integer, String> locations = new TreeMap<Integer, String>();
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(currentFile), ENCODING), 8096);
            String str = "";
            if (firstRowAsHeader) {
                str = in.readLine();
            }

            String[] header = SPLIT_ON_TAB.split(str);

            while ((str = in.readLine()) != null) {

                String[] strParts = SPLIT_ON_TAB.split(str);
                
                StringBuilder keys = new StringBuilder(strParts[0]);
                if(strParts.length>8 && !strParts[8].isEmpty()){
                    keys.append(";").append(strParts[8]);
                }
                
                if (!strParts[5].isEmpty()) {
                    //System.out.println(strParts[5]);
                    if (Double.parseDouble(strParts[5]) >= minMaf) {
                        if (locations.size()>0) {
                            if(locations.containsKey(Integer.parseInt(strParts[3])) && strParts.length>8){
                                StringBuilder newKeys = new StringBuilder(locations.get(Integer.parseInt(strParts[3])));
                                newKeys.append(";").append(strParts[8]);
                                locations.put(Integer.parseInt(strParts[3]), newKeys.toString());
                            } else{
                                locations.put(Integer.parseInt(strParts[3]), keys.toString());
                            }
                        } else {
                            locations.put(Integer.parseInt(strParts[3]), keys.toString());
                            currectChr = strParts[2];
                        }
                    }
                }
            }
            snpInfo.put(currectChr, locations);
            
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            System.exit(-1);
        }
    }
    
    return (snpInfo);
}