Search Results

Search found 16 results on 1 pages for 'sortedmap'.

Page 1/1 | 1 

  • How to do inclusive range queries when only half-open range is supported (ala SortedMap.subMap)

    - by polygenelubricants
    On SortedMap.subMap This is the API for SortedMap<K,V>.subMap: SortedMap<K,V> subMap(K fromKey, K toKey) : Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. This inclusive lower bound, exclusive upper bound combo ("half-open range") is something that is prevalent in Java, and while it does have its benefits, it also has its quirks, as we shall soon see. The following snippet illustrates a simple usage of subMap: static <K,V> SortedMap<K,V> someSortOfSortedMap() { return Collections.synchronizedSortedMap(new TreeMap<K,V>()); } //... SortedMap<Integer,String> map = someSortOfSortedMap(); map.put(1, "One"); map.put(3, "Three"); map.put(5, "Five"); map.put(7, "Seven"); map.put(9, "Nine"); System.out.println(map.subMap(0, 4)); // prints "{1=One, 3=Three}" System.out.println(map.subMap(3, 7)); // prints "{3=Three, 5=Five}" The last line is important: 7=Seven is excluded, due to the exclusive upper bound nature of subMap. Now suppose that we actually need an inclusive upper bound, then we could try to write a utility method like this: static <V> SortedMap<Integer,V> subMapInclusive(SortedMap<Integer,V> map, int from, int to) { return (to == Integer.MAX_VALUE) ? map.tailMap(from) : map.subMap(from, to + 1); } Then, continuing on with the above snippet, we get: System.out.println(subMapInclusive(map, 3, 7)); // prints "{3=Three, 5=Five, 7=Seven}" map.put(Integer.MAX_VALUE, "Infinity"); System.out.println(subMapInclusive(map, 5, Integer.MAX_VALUE)); // {5=Five, 7=Seven, 9=Nine, 2147483647=Infinity} A couple of key observations need to be made: The good news is that we don't care about the type of the values, but... subMapInclusive assumes Integer keys for to + 1 to work. A generic version that also takes e.g. Long keys is not possible (see related questions) Not to mention that for Long, we need to compare against Long.MAX_VALUE instead Overloads for the numeric primitive boxed types Byte, Character, etc, as keys, must all be written individually A special check need to be made for toInclusive == Integer.MAX_VALUE, because +1 would overflow, and subMap would throw IllegalArgumentException: fromKey > toKey This, generally speaking, is an overly ugly and overly specific solution What about String keys? Or some unknown type that may not even be Comparable<?>? So the question is: is it possible to write a general subMapInclusive method that takes a SortedMap<K,V>, and K fromKey, K toKey, and perform an inclusive-range subMap queries? Related questions Are upper bounds of indexed ranges always assumed to be exclusive? Is it possible to write a generic +1 method for numeric box types in Java? On NavigableMap It should be mentioned that there's a NavigableMap.subMap overload that takes two additional boolean variables to signify whether the bounds are inclusive or exclusive. Had this been made available in SortedMap, then none of the above would've even been asked. So working with a NavigableMap<K,V> for inclusive range queries would've been ideal, but while Collections provides utility methods for SortedMap (among other things), we aren't afforded the same luxury with NavigableMap. Related questions Writing a synchronized thread-safety wrapper for NavigableMap On API providing only exclusive upper bound range queries Does this highlight a problem with exclusive upper bound range queries? How were inclusive range queries done in the past when exclusive upper bound is the only available functionality?

    Read the article

  • Java SortedMap to Scala TreeMap

    - by Dave
    I'm having trouble converting a java SortedMap into a scala TreeMap. The SortedMap comes from deserialization and needs to be converted into a scala structure before being used. Some background, for the curious, is that the serialized structure is written through XStream and on desializing I register a converter that says anything that can be assigned to SortedMap[Comparable[_],_] should be given to me. So my convert method gets called and is given an Object that I can safely cast because I know it's of type SortedMap[Comparable[_],_]. That's where it gets interesting. Here's some sample code that might help explain it. // a conversion from comparable to ordering scala> implicit def comparable2ordering[A <: Comparable[A]](x: A): Ordering[A] = new Ordering[A] { | def compare(x: A, y: A) = x.compareTo(y) | } comparable2ordering: [A <: java.lang.Comparable[A]](x: A)Ordering[A] // jm is how I see the map in the converter. Just as an object. I know the key // is of type Comparable[_] scala> val jm : Object = new java.util.TreeMap[Comparable[_], String]() jm: java.lang.Object = {} // It's safe to cast as the converter only gets called for SortedMap[Comparable[_],_] scala> val b = jm.asInstanceOf[java.util.SortedMap[Comparable[_],_]] b: java.util.SortedMap[java.lang.Comparable[_], _] = {} // Now I want to convert this to a tree map scala> collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k)) }) <console>:15: error: diverging implicit expansion for type Ordering[A] starting with method Tuple9 in object Ordering collection.immutable.TreeMap() ++ (for(k <- b.keySet) yield { (k, b.get(k)) })

    Read the article

  • Clojure: I have many sorted maps and want to reduce in order all there values a super maps of keys -> vector

    - by Alex Foreman
    I have seen this but can't work out how to apply it (no pun intended) to my situation. I have a sorted list of maps like this: (note there can be more than two keys in the map) ({name1 3, name2 7}, {name1 35, name2 7}, {name1 0, name2 3}) What I am after is this data structure afterwards: ({:name1 [3,35,0]}, {:name2 [7,7,3]}) Ive been struggling with this for a while and cant seem to get anywhere near. Caveats: The data must stay sorted and I have N keywords not just two.

    Read the article

  • How to implement collection with covariance when delegating to another collection for storage?

    - by memelet
    I'm trying to implement a type of SortedMap with extended semantics. I'm trying to delegate to SortedMap as the storage but can't get around the variance constraints: class IntervalMap[A, +B](implicit val ordering: Ordering[A]) //extends ... { var underlying = SortedMap.empty[A, List[B]] } Here is the error I get. I understand why I get the error (I understand variance). What I don't get is how to implement this type of delegation. And yes, the covariance on B is required. error: covariant type B occurs in contravariant position in type scala.collection.immutable.SortedMap[A,List[B]] of parameter of setter underlying_=

    Read the article

  • Java: How to workaround the lack of Equatable interface?

    - by java.is.for.desktop
    Hello, everyone! As far as I know, things such as SortedMap or SortedSet, use compareTo (rather than equals) on Comparable<?> types for checking equality (contains, containsKey). But what if certain types are equatable by concept, but not comparable? I have to declare a Comparator<?> and override the method int compareTo(T o1, To2). OK, I can return 0 for instances which are considered equal. But, for unqeual instances, what do I return when an order is not evident? Is the approach of using SortedMap or SortedSet on equatable but (by concept) not comparable types good anyway? Thank you! EDIT: I don't want to store things sorted, but would I use "usual" Map and Set, I couldn't "override" the equality-behavior. EDIT 2: Why I can't just override equals(...): I need to alter the equality-behavior of a foreign class. Can't edit it. EDIT 3: Just think of .NET: They have IEquatable interface which cat alter the equality-behavior without touching the comparable behavior.

    Read the article

  • Writing a synchronized thread-safety wrapper for NavigableMap

    - by polygenelubricants
    java.util.Collections currently provide the following utility methods for creating synchronized wrapper for various collection interfaces: synchronizedCollection(Collection<T> c) synchronizedList(List<T> list) synchronizedMap(Map<K,V> m) synchronizedSet(Set<T> s) synchronizedSortedMap(SortedMap<K,V> m) synchronizedSortedSet(SortedSet<T> s) Analogously, it also has 6 unmodifiedXXX overloads. The glaring omission here are the utility methods for NavigableMap<K,V>. It's true that it extends SortedMap, but so does SortedSet extends Set, and Set extends Collection, and Collections have dedicated utility methods for SortedSet and Set. Presumably NavigableMap is a useful abstraction, or else it wouldn't have been there in the first place, and yet there are no utility methods for it. So the questions are: Is there a specific reason why Collections doesn't provide utility methods for NavigableMap? How would you write your own synchronized wrapper for NavigableMap? Glancing at the source code for OpenJDK version of Collections.java seems to suggest that this is just a "mechanical" process Is it true that in general you can add synchronized thread-safetiness feature like this? If it's such a mechanical process, can it be automated? (Eclipse plug-in, etc) Is this code repetition necessary, or could it have been avoided by a different OOP design pattern?

    Read the article

  • My method is too specific. How can I make it more generic?

    - by EricBoersma
    I have a class, the outline of which is basically listed below. import org.apache.commons.math.stat.Frequency; public class WebUsageLog { private Collection<LogLine> logLines; private Collection<Date> dates; WebUsageLog() { this.logLines = new ArrayList<LogLine>(); this.dates = new ArrayList<Date>(); } SortedMap<Double, String> getFrequencyOfVisitedSites() { SortedMap<Double, String> frequencyMap = new TreeMap<Double, String>(Collections.reverseOrder()); //we reverse order to sort from the highest percentage to the lowest. Collection<String> domains = new HashSet<String>(); Frequency freq = new Frequency(); for (LogLine line : this.logLines) { freq.addValue(line.getVisitedDomain()); domains.add(line.getVisitedDomain()); } for (String domain : domains) { frequencyMap.put(freq.getPct(domain), domain); } return frequencyMap; } } The intention of this application is to allow our Human Resources folks to be able to view Web Usage Logs we send to them. However, I'm sure that over time, I'd like to be able to offer the option to view not only the frequency of visited sites, but also other members of LogLine (things like the frequency of assigned categories, accessed types [text/html, img/jpeg, etc...] filter verdicts, and so on). Ideally, I'd like to avoid writing individual methods for compilation of data for each of those types, and they could each end up looking nearly identical to the getFrequencyOfVisitedSites() method. So, my question is twofold: first, can you see anywhere where this method should be improved, from a mechanical standpoint? And secondly, how would you make this method more generic, so that it might be able to handle an arbitrary set of data?

    Read the article

  • Unmodifiable NavigableSet/NavigableMap in Java?

    - by Greg Mattes
    java.util.Collections has several unmodifiable methods that provide unmodifiable collection views by wrapping collections in decorators that prohibit mutation operations. Java 6 added support for java.util.NavigableSet and java.util.NavigableMap. I'd like to be able to have unmodifiable NavigableSets and NavigableMaps, but java.util.Collections#unmodifiableSortedSet(SortedSet) and java.util.Collections#unmodifiableSortedMap(SortedMap) are not sufficient because they do not support the operations that are particular to NavigableSet and NavigableMap. Are there de-facto implementations for unmodifiableNavigableSet and unmodifiableNavigableMap?

    Read the article

  • How to sort hashmap?

    - by agazerboy
    Hi All ! I have hashmap and its keys are like "folder/1.txt,folder/2.txt,folder/3.txt" and value has these text files data. Now i am stucked. I want to sort this list. But it does not let me do it :( Here is my hashmap data type: HashMap<String, ArrayList<String>> following function work good but it is for arraylist not for hashmap. Collections.sort(values, Collections.reverseOrder()); I also tried MapTree but it also didn't work, or may be I couldn't make it work. I used following steps to sort the code with maptree HashMap testMap = new HashMap(); Map sortedMap = new TreeMap(testMap); any other way to do it?? I have one doubt as my keys are (folder/1.txt, folder/2.txt ) may be that's why?

    Read the article

  • How to sort Map in Java

    - by kalpesh
    hi i want to sort map according to its key value plz see code below public static void main(String[] args) { SortedMap map = new TreeMap(); // Add some elements: map.put("2", "Two"); map.put("1", "One"); map.put("5", "Five"); map.put("4", "Four"); map.put("3", "Three"); map.put("10", "Ten"); map.put("12", "Twelve"); map.put("7", "Seven"); map.put("9", "Nine"); Iterator iterator = map.keySet().iterator(); while (iterator.hasNext()) { Object key = iterator.next(); System.out.println("key : " + key + " value :" + map.get(key)); } } Result Should come below key : 1 value :One key : 2 value :Two key : 3 value :Three key : 4 value :Four key : 5 value :Five key : 7 value :Seven key : 9 value :Nine key : 10 value :Ten key : 12 value :Twelve

    Read the article

  • google collections ordering on map values

    - by chris-gr
    I would like to order a map based on the values. Function<Map.Entry<A, Double>, Double> getSimFunction = new Function<Map.Entry<A, Double>, Double>() { public Double apply(Map.Entry<A, Double> entry) { return entry.getValue(); } }; final Ordering<Map.Entry<A, Double>> entryOrdering = Ordering.natural().onResultOf(getSimFunction); ImmutableSortedMap.orderedBy(entryOrdering).putAll(....).build(); How can I create a new sortedMap based on the ordering results or a sortedset based on the map.keyset()?

    Read the article

  • Data Structures usage and motivational aspects

    - by Aubergine
    For long student life I was always wondering why there are so many of them yet there seems to be lack of usage at all in many of them. The opinion didn't really change when I got a job. We have brilliant books on what they are and their complexities, but I never encounter resources which would actually give a good hint of practical usage. I perfectly understand that I have to look at problem , analyse required operations, look for data structure that does them efficiently. However in practice I never do that, not because of human laziness syndrome, but because when it comes to work I acknowledge time priority over self-development. Over time I thought that when I would be better developer I will automatically use more of them - that didn't happen at all or maybe I just didn't. Then I found that the colleagues usually in the same plate as me - knowing more or less some three of data structures and being totally happy about it and refusing to discuss this matter further with me, coming back to conversations about 'cool new languages' 'libraries that do jobs for you' and the joy to work under scrumban etc. I am stuck with ArrayLists, Arrays and SortedMap , which no matter what I do always suffice or either I tweak them to be capable of fulfilling my task. Yes, it might be inefficient but do we really have to care if Intel increases performance over years no matter if we improve our skills? Does new Xeon or IBM machines really care what we use? What if I like build things, but I am not particularly excited whether it is n log(n) or just n? Over twenty years the processing power increased enormously, which gives us freedom of not being critical about which one to use? On top of that new more optimized languages appear which support multiple cores more efficiently. To be more specific: I would like to find motivational material on complex real areas/cases of possible effective usages of data structures. I would be really grateful if you would provide relevant resources. There is similar question ,but in the end the links again mostly describe or do dumb example(vehicles, students or holy grail quest - yes, very relevant) them and people keep referring to the "scenario decides the data structure to use". I want to know these complex scenarios to be able to identify similarities to my scenario and then use them. The complex scenarios where it really matters and not necessarily of quantitive nature. It seems that data structures only concern is efficiency and nothing else? There seems to be no particular convenience for developer in use one over another. (only when I found scientific resources on why exactly simple carbohydrates are evil I stopped eating sugar and candies completely replacing it with less harmful fruits - I hope you can see the analogy)

    Read the article

  • Difference between HashMap, LinkedHashMap and SortMap in java

    - by theband
    Map m1 = new HashMap(); m1.put("map", "HashMap"); m1.put("schildt", "java2"); m1.put("mathew", "Hyden"); m1.put("schildt", "java2s"); print(m1.keySet()); print(m1.values()); SortedMap sm = new TreeMap(); sm.put("map", "TreeMap"); sm.put("schildt", "java2"); sm.put("mathew", "Hyden"); sm.put("schildt", "java2s"); print(sm.keySet()); print(sm.values()); LinkedHashMap lm = new LinkedHashMap(); lm .put("map", "LinkedHashMap"); lm .put("schildt", "java2"); lm .put("mathew", "Hyden"); lm .put("schildt", "java2s"); print(lm .keySet()); print(lm .values()); What is the difference between these three? I don't see any difference in the output as all the three has keySet and values. What are Hashtables?

    Read the article

  • Database insertion not happening

    - by Pramod Setlur
    int i=0; ContentValues values = null; for ( SortedMap.Entry<Integer, String> entry : mapDefect.entrySet() ) { if( i++ < count ) continue; if( i < arrlst.size() ) { values = new ContentValues(); Log.d("MAP", "Id :"+entry.getKey()+"Des :"+entry.getValue()+"Co :"+ arrlst.get(i)); values.put( MARKER_COORD, arrlst.get( i ) ); values.put( MARKER_ID, entry.getKey() ); values.put( DEFECT_DESCRIPTION, entry.getValue() ); values.put( IMAGE_ID_F, imageID + 1 ); Log.d( "Err", "in insertNewDefectsDescription" ); long rowId = db.insert( TABLE_DEFECTS, null, values ); long rowId1 = rowId; i++; } } So, I want to access the arraylist only after the count variable, which is why the:- if(i++<count) continue; But, when I insert a break point at the 'insert' line, it is not working. The line is not executing at all, and hence the data is not being inserted into the database. What has gone wrong?? The 'values' are null.

    Read the article

1