Keeping track of the number of occurrences in a map will allow you to do this. import java.util.HashMap; import java.util.Map.Entry; import java.util.Set; public class Test1 { public static void main(String[] args) { String string1="world world is new world of kingdom of palace of kings palace"; String string2[]=string1.split(" "); HashMap<String, Integer>...
lowerKey() is a search in a balanced binary search tree, so it's obviously O(log n). You might want to read the source code, e.g. from here, to see how the tree is traversed. Similarly, each operation with a NavigableMap returned from subMap() also requires O(log n) because you will need...
TreeMap has a constructor that takes a Comparator as an argument. The comparator is used to order keys stored in the map. If you literally want to "count the number of comparisons carried out", you could write an instrumented comparator that counts the number of times it's called. public class...
The entrySet of a map is a set of Map.Entry<KeyType, ValueType>s. You have this: Collection entrySet = al.entrySet(); Iterator<Student> itr = entrySet.iterator(); If you weren't using a raw type in the first line, the error would be much more obvious. Never use raw types: Collection<Student> entrySet = al.entrySet(); // ERROR...
java,hashmap,treemap,linkedhashmap
When iterating a Hashmap, there will be no guarantee about the iteration order. Now why is that? They're inserted not in order of when they occurred, but what value they hash to. For example, suppose that we have a hash function h(x) which returns 127 for the string "Hello",...
The canonical way of doing this is to use Collections.singletonMap() Nice and simple, provided that you also require (or at least, don't mind) immutability. And yes, internally it is implemented as a custom single-node Map. As a complete aside, you can create a HashMap with a single bucket if in...
That's because the default String Comparator uses lexicographical order -- i.e. character by character, as in a dictionary. Since "1" comes before "2", any String starting with "1" will precede any other starting with "2". You could create your own custom comparator to implement Natural Sorting and supply it to...
You can use Collections.sort(list, comparator), where you have to implement a Comparator<Map<String,?>> to do what you need (i.e. retrieve the sent_date from two maps and compare those).
for (Date d: produkt.keySet()){ System.out.println( d + " pocet:" + produkt.get(d)); if (d.before(now)) { obsah.get(name).remove(d); } } You cannot remove an element from a collection while iterating it, this is causing the error. You should use the fact that you have TreeMap, that maintains order of the elements, so...
Check this, I fix the part where you read from text file and populate the TreeMap. I tested and works fine. public class Map { private TreeMap<String, String> pairs; public Map() { pairs = new TreeMap<String, String>(); } public void readFrom(String fileName) { try { Scanner input = new Scanner(new...
tl;dr: Here's how it should be done: def time = (1..10) def timeWithIdentifier = [:] for (i = 0; i <= time.size()-1; i++) { timeWithIdentifier[i] = time[i] } new TreeMap(timeWithIdentifier) Explanation: As can be seen here TreeMap doesn't take an ArrayList as constructor argument - Map should be passed. When...
.get() is attempting to use the key of the map that you've declared. Since you want to find the value within Map[A][B], then you should refer to it as such: int x = routes.get("A").get("B"); ...
You can use entrySet instead of keySet. This way it would take O(1) to find out if a given value belongs to the key you wish to exclude. You can call entrySet any time you need to iterate over the values, and exclude the bad key while iterating over them....
java,dictionary,hashmap,treemap
If you need the map sorted by its keys, then use TreeMap, which "...provides guaranteed log(n) time cost for the containsKey, get, put and remove operations." If not, use the more general HashMap (which "...provides constant-time performance for the basic operations (get and put), assuming the hash function disperses the...
java,iterator,key-value,treemap
Something like this? TreeMap<String, List<String>> treeMap3 = new TreeMap<>(treeMap1); for (String k : treeMap3.keySet()) { if (treeMap2.containsKey(k)) { treeMap3.get(k).addAll(treeMap2.get(k)); } } return treeMap3; ...
java,sorting,iterator,hex,treemap
See your code here: Set<Map.Entry<String, String>> buttons = buttonColors.entrySet(); Iterator sortingItr = buttons.iterator(); while (sortingItr.hasNext()) { Map.Entry<String, String> entry = (Map.Entry) sortingItr.next(); ^^^^^^^^^^^^^^^^^ System.out.println(sortingItr.next()); ^^^^^^^^^^^^^^^^^^ } See that you are calling next method twice. So you are advancing the cursor of iterator by calling next method on iterator two times...
You can provide your own custom Comparator: public class LowerCaseFirstComaparor implements Comparator<Character> { @Override public int compare (Character c1, Character c2) { if (Character.isLowerCase(c1)) { if (Character.isLowerCase(c2)) { return c1.compareTo(c2); } else { return -1; } } else if (Character.isLowerCase(c2)) { return 1; } else { return c1.compareTo(c2); } }...
Your problem is that if two entries of your original map have the same value, then only the last inserted in freq will remain. Therefore the key that has been replaced in freq is removed from the treemap. Example: freq.put("bara" , 0.1142204454597373); freq.put("religieux" , 0.05711022272986865); freq.put("alliance" , 0.05711022272986865); then freq.get("religieux")...
javascript,d3.js,javascript-events,mouseover,treemap
The error Uncaught SyntaxError: Unexpected token is probably caused by Javascript files which are loaded in your basic code example: https://gist.github.com/vibster/3257874 These files in the header contains bad url to source code: <script type="text/javascript" src="https://github.com/mbostock/d3/blob/master/src/layout/treemap.js"></script> <script type="text/javascript" src="https://github.com/mbostock/d3/blob/master/src/layout/hierarchy.js"></script> If you open the url e.g. of the first source It contains...
At I see at this moment you can catch redraw event and prepare a simple "parser" which check id. Default structure of that is id_1 for first level, id_1_1 for second level. The simplest is use a split, and check length of array. Obviosuly this is very poor solution. events:...
Check your comparator code. Does comparing "0" and "0" return 0, as it should? No it doesn't, since you don't check for equality if your string starts with a digit. You also don't return proper ordering if two strings both start with digits.
Your compare method is flawed, because it can't return 0. If the two objects are equal, then it needs to return 0, not 1. Change your compare method to return 0 if the two Integers are equal. This will allow the TreeMap to find the Integer, which relies on compare...
Please re-read the TreeMap Javadocs - or the generic Map interface, for that matter - and be very familiar with them for what you're trying to do here. .containsValue() will search for specific, exact matches in the domain of values that you have inserted into your Map - nothing more,...
java,performance,duplicates,treemap
The most efficient implementation really depends on your requirements. From what you've written: So, I have a large file containing 3 million lines of words. And I need to see if there is any duplicates., I assume you're only looking to check whether there is a duplicate line. In such...
java,data-structures,treemap,linkedhashmap
The source code for the normal implementations is in the src.zip file that comes with the Oracle JDK installs. TreeMap: As indicated in its documentation, it is a Red-Black tree. The critical code for simple forwards iteration over the keys is the method static <K,V> TreeMap.Entry<K,V> successor(Entry<K,V> t). It recursively...
The set method does not create a new Calendar, it is still the same but with a different value. Therefore, when you add it to the Map it simply updates the value as its the same key, you are always referencing the same object. You need to create a new...
I think you're on the right track. Unfortunately, "manual" treemap assume linear vColor scales. I will add an argument to change legend break labels. For the time being, you could modify the labels in the plotted grid object....
You have to iterate over the entries on your first TreeMap. for(Map.Entry<String, List<String>> entry : first.entrySet()) { For each entry grab the oldKey and the oldValues. String oldKey= entry.getKey(); List<String> oldValues= entry.getValue(); Create the newKey String newKey = origin.get(oldKey); Then iterate over each value s in oldValues to get the...
According to the implementation in the Open JDK, it is O(log N): public K lastKey() { return key(getLastEntry()); } final Entry<K,V> getLastEntry() { Entry<K,V> p = root; if (p != null) while (p.right != null) p = p.right; return p; } The lastKey() calls getLastEntry(), which continues to take the...
I don't have enough rep for a comment... sorry. What version of GWT are you using? It looks like there is a bug here: https://code.google.com/p/google-web-toolkit/issues/detail?id=4236 Fixed in 2.7.0 RC1...
java,sorting,map,comparator,treemap
You need to modify logic as below, handle all three cases of -1, 0 and 1 public int compare(Integer a, Integer b) { if (base.get(a).charAt(0) == base.get(b).charAt(0)) return 0; else if (base.get(a).charAt(0) > base.get(b).charAt(0)) return 1; else return -1; } output 2 a 0 b 1 c ...
java,serialization,soap,treemap
As pointed out by @PaulVargas in the comments, TreeMap is not directly supported by JAX-B. I resolved this issue creating my TreeMapSerializer adapting this answer JAXB: How to suppress surrounding XmlElement when using XmlJavaTypeAdapter?...
The way you want to display your content varies depending on your requirement or on how the information could be displayed in an user-friendly way. JTable is a good approach, JTree also is a good approach, although, I see JTable as a more standard way to do it. I came...
You need to return 0; when you expect a match. The way to solve this is to compare the key which it is otherwise a match. This way the same key will match, but only the same key. public int compare(String a, String b) { int cmp = -map.get(a).compareTo(map.get(b)); if...
java,for-loop,double,treemap,double-precision
You just ran into one of the main problems in mathematical coding! Congratulations! This is a really annoying one in general, but in your case it's quite solvable. Check out the answer to this question and apply it to your code and it should be fixed. Round a double to...
One way you could try is to make a multimap of key->maps, i.e. iterate over all 500k maps and add them for each key they contain. Then iterate over the keys again and if there are two or more maps for a key, those maps share it. With that approach...
java,dictionary,collections,hashmap,treemap
for (DLFolder dlf : treePath.values()) { if ("A SPECIFIC PATH".equals(dlf.getPath()) { // do someting with the dlf } ...
See http://docs.oracle.com/javase/6/docs/api/java/text/SimpleDateFormat.html. Use y for year, M for month in year, and d for day in month. Specifically, lowercase m is minute in hour, while uppercase M is month in year....
java,map,hashmap,key-value,treemap
with current data-structure you must loop over the map: ArrayList<String> relatedKeys = new ArrayList<String>(); for(String k : departmentList.keySet()){ if(departmentList.get(k).equals(searchKey)) relatedKeys.add(k); at the end, you have a list of all related keys and can use for(String k : relatedKeys) System.out.println(k); ...
TreeMap for a String key would use String lexicographical order by default (that's the natural ordering for Strings), unless you supply your own Comparator in the constructor. A2:A8 comes after A20:A26 when using lexicographical order. Your comparator would probably have to split the String key into 4 parts (for example,...
Some of the answers already point to the currect answer. But lets assume you have two input Strings with the username and password of a user you want to validate: if (userInfo.contains(username)){ if(userInfo.get(username).getLast().equals(password){ return true; } else { //Bad password return false; } } //Unknown user return false; ...
When writing a comparator it's important to ensure that the results are consistent (i.e. are the same over time) and that it implements a total order. When using the comparator in a TreeMap it is also required that it is consistent with equals, which means that c.compare(e1, e2) return 0...
TreeMap is an ordered container: when you request its keys or its entries, you get them in a certain order. The order depends on the key that you supply. In order for the container to order the keys, each key needs to implement Comparable interface: class GeneKey implements Comparable<GeneKey> {...
As others have pointed out, the values will be replaced since a Map only allows one key -> value mapping. The easiest way of mapping multiple values to a key is to use a multi(value)map. I prefer Guava for this: Scanner scanner = new Scanner(new FileReader("marks.txt")); TreeMultimap<String, Integer> students =...
You're creating a TreeSet, whereas, you need to create a TreeMap. The comparator which you pass to TreeMap, will use the map passed as parameter, to fetch the value and compare them. Change your method to: static <K, V extends Comparable<? super V>> TreeMap<K, V> entriesSortedByValues(final Map<K, V> map) {...
java,android,sorting,sharedpreferences,treemap
Provide the TreeMap with a custom Comparator and it will use that to sort the entries in the map however you need.
I figured it out by my own. The key was to create a TreeMap with not two list but two single Objects: Map<String, Drawable> myTreeMap = new TreeMap<String, Drawable>; Then add the Items from the Arraylists one by one to the Map: for(int i = 0; i<names.size(); i++) { myTreeMap.put(names.get(i),...
Assuming both maps are instances of Map<String, List<String>>, you can do: // init result set with keys from treemapOne Set<String> remainingKeys = new HashSet<>(treemapOne.keySet()); // remove keys in treemapTwo remainingKeys.removeAll(treemapTwo.keySet()); // remove values in treemapTwo for (List<String> values : treemapTwo.valueSet()) { remainingKeys.removeAll(values); } ...
javascript,mysql,database,structure,treemap
As Neo M Hacker said, neo4j is great for this sort of thing. You tagged with mySQL, though, so if you're stuck with an relational database, the best solution I've seen is to have an "ancestors" column which stores a delineated list of IDs of ancestors up the tree. That...
java,string,if-statement,duplicates,treemap
Create a set to contain the full names of the departments already output. Each time you want to output a department, check if the set contains it already. If not, then output the department name and add it to the set. For example: Set<String> usedDepartments = new HashSet<String>(); Then in...
Cache means to have it memory, you are already putting each line in memory line = inputStream.readLine() and then discarding that in next loop iteration. you have mentioned you want to store it in TreeMap, you need to decide what will be the key?, as the TreeMap is sorted, how...