Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
If I have an object implementing the Map interface in Java and I wish to iterate over every pair contained within it, what is the most efficient way of going through the map? Will the ordering of elements depend on the specific map implementation that I have for the interface?
In Java, Is there an object that acts like a Map for storing and accessing key/value pairs, but can return an ordered list of keys and an ordered list of values, such that the key and value lists are in the same order? So as explanation-by-code, I'm looking for something that behaves like my fictitious OrderedMap: OrderedMap om = new OrderedMap(); om.put(0, "Zero"); om.put(7, "Seven"); Objec...
I understand that the Set returned from a Map's keySet() method does not guarantee any particular order. My question is, does it guarantee the same order over multiple iterations. For example Map<K,V> map = getMap(); for( K k : map.keySet() ) { } ... for( K k : map.keySet() ) { } In the above code, assuming that the map is not modified, will the iteration over the keySets be in th...
How to move a particular HashMap entry to Last position? For Example, I have HashMap values like this: HashMap<String,Integer> map = new HashMap<String,Integer>(); map= {Not-Specified 1, test 2, testtest 3}; "Not-Specified" may come in any position. it may come first or in the middle of the map. But i want to move the "Not-Specified" to the last position. How can I do that? th...
I was wandering if there is a class out there that implements both Map and List interfaces in Java. I have a data structure that is primarily a Map. I map strings (IDs) to Images. But in a specific part of my code i need to present the user with all the available IDed Images. The only way to do that so far is to write this : for (String id : myMap.keySet()) { // get the image like this "...
I'm new to java, i want to write an comparator to that will let me sort TreeMap by value instead of the default natural sorting. i tried something like this, but can't find out what went wrong: import java.util.*; class treeMap { public static void main(String[] args) { System.out.println("the main"); byValue cmp = new byValue(); Map<String, Integer> map = ne...
Is there any reason to use SortedMap instead of NavigableMap, besides the JVM version? (NavigableMap has only been there since 1.6; SortedMap has been there since 1.2) I'm trying to find the value with the greatest key such that key <= reference key K0. I can't seem to figure out how to do this with a SortedMap (if it were strictly <, then I'd call headMap() and then lastKey() and then g...
I have a situation whereby I'm populating an ArrayList with "TransactionEvent"s. TransactionEvent has a property "transaction ID". In the large majority of cases each new event has a transaction ID greater the previous event's ID - However, this is not guaranteed; i.e. the data is almost sorted. My question is this: How can I perform fast look-ups based on transaction ID? My current idea is...
My problem Let's say I want to hold my messages in some sort of datastructure for longpolling application: 1. "dude" 2. "where" 3. "is" 4. "my" 5. "car" Asking for messages from index[4,5] should return: "my","car". Next let's assume that after a while I would like to purge old messages because they aren't useful anymore and I want to save memory. Let's say after time x messages[1-3] beca...
This should be easy for many of you, but for me it's just another bit of rust needing to be chipped away as I get back into basic Java coding. Using bloody associative arrays for so long in other languages have turned me nice and spoiled. :P My problem is simple: I'm storing a set of objects, each containing a string and a number, in a list. I would like each object inserted into this list t...
I started learning Java. When do use Hashmap over Treemap?
If we have a Map<T, Integer>, let's say the Integer value represents "how many" Ts there are. Thus, I want to uniformly select a T based on its Integer value. If the map contains Strings with "a"=4 and "b"=6, then I want it so that 40% of the time "a" is selected and 60% of the time "b" is selected. Most importantly, I'd like this in O(n), n being two (not ten) in my previous example. I ...
first time poster, long time reader so be gentle with me :) See the following code which works to generate me timestamps for the beginning and end of every month in a financial year. int year = 2010; // Financial year runs from Sept-Aug so earlyMonths are those where year = FY-1 and lateMonths are those where year = FY int[] earlyMonths = {8, 9, 10, 11}; // Sept to Dec int earlyYear = year -1...
I was wondering how Java orders items in the Map (HashMap or Hashtable) when they are added. Are the keys ordered by the hashcode, memory reference or by allocation precedence...? It's because I've noticed same pairs in the Map are not always in the same order
How to accept multiple username and password using the following code? if (value1.equals("username") && value2.equals("password"))
Why is Java Comparable used? Why would someone implement Comparable in a class? I've seen it I'm just wondering what it is for. Can someone give me real life example when would you implement comparable?
This question was asked in an interview . Except Collections.sort() what are the other methods .
Possible Duplicate: How to sort a Map<Key, Value> on the values in Java? I have a HashMap of the type: HashMap<String, Integer> h = new HashMap<String, Integer>(); The HashMap contains a list of Strings and the Integer is a counter for the number of times that String has been found. What I would like to be able to do is sort the HashMap based on the Integers, the...
I have a text file with Tag - Value format data. I want to parse this file to form a Trie. What will be the best approach? Sample of File: (String inside "" is a tag and '#' is used to comment the line.) #Hi, this is a sample file. "abcd" = 12; "abcde" = 16; "http" = 32; "sip" = 21;
Given this map SortedMap<Integer, String> myMap = new TreeMap<Integer, String>(); Instead of a for loop is there a utility function to copy first N items to a destination map?
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(...
  /*
   * Copyright 1998-2006 Sun Microsystems, Inc.  All Rights Reserved.
   * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   *
   * This code is free software; you can redistribute it and/or modify it
   * under the terms of the GNU General Public License version 2 only, as
   * published by the Free Software Foundation.  Sun designates this
   * particular file as subject to the "Classpath" exception as provided
   * by Sun in the LICENSE file that accompanied this code.
  *
  * This code is distributed in the hope that it will be useful, but WITHOUT
  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  * version 2 for more details (a copy is included in the LICENSE file that
  * accompanied this code).
  *
  * You should have received a copy of the GNU General Public License version
  * 2 along with this work; if not, write to the Free Software Foundation,
  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  *
  * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
  * CA 95054 USA or visit www.sun.com if you need additional information or
  * have any questions.
  */
 
 package java.util;

A Map that further provides a total ordering on its keys. The map is ordered according to the natural ordering of its keys, or by a Comparator typically provided at sorted map creation time. This order is reflected when iterating over the sorted map's collection views (returned by the entrySet, keySet and values methods). Several additional operations are provided to take advantage of the ordering. (This interface is the map analogue of SortedSet.)

All keys inserted into a sorted map must implement the Comparable interface (or be accepted by the specified comparator). Furthermore, all such keys must be mutually comparable: k1.compareTo(k2) (or comparator.compare(k1, k2)) must not throw a ClassCastException for any keys k1 and k2 in the sorted map. Attempts to violate this restriction will cause the offending method or constructor invocation to throw a ClassCastException.

Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if the sorted map is to correctly implement the Map interface. (See the Comparable interface or Comparator interface for a precise definition of consistent with equals.) This is so because the Map interface is defined in terms of the equals operation, but a sorted map performs all key comparisons using its compareTo (or compare) method, so two keys that are deemed equal by this method are, from the standpoint of the sorted map, equal. The behavior of a tree map is well-defined even if its ordering is inconsistent with equals; it just fails to obey the general contract of the Map interface.

All general-purpose sorted map implementation classes should provide four "standard" constructors: 1) A void (no arguments) constructor, which creates an empty sorted map sorted according to the natural ordering of its keys. 2) A constructor with a single argument of type Comparator, which creates an empty sorted map sorted according to the specified comparator. 3) A constructor with a single argument of type Map, which creates a new map with the same key-value mappings as its argument, sorted according to the keys' natural ordering. 4) A constructor with a single argument of type SortedMap, which creates a new sorted map with the same key-value mappings and the same ordering as the input sorted map. There is no way to enforce this recommendation, as interfaces cannot contain constructors.

Note: several methods return submaps with restricted key ranges. Such ranges are half-open, that is, they include their low endpoint but not their high endpoint (where applicable). If you need a closed range (which includes both endpoints), and the key type allows for calculation of the successor of a given key, merely request the subrange from lowEndpoint to successor(highEndpoint). For example, suppose that m is a map whose keys are strings. The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, inclusive:

   SortedMap<String, V> sub = m.subMap(low, high+"\0");
A similar technique can be used to generate an open range (which contains neither endpoint). The following idiom obtains a view containing all of the key-value mappings in m whose keys are between low and high, exclusive:
   SortedMap<String, V> sub = m.subMap(low+"\0", high);

This interface is a member of the Java Collections Framework.

Parameters:
<K> the type of keys maintained by this map
<V> the type of mapped values
Author(s):
Josh Bloch
Since:
1.2
See also:
Map
TreeMap
SortedSet
Comparator
java.lang.Comparable
Collection
java.lang.ClassCastException
public interface SortedMap<K,V> extends Map<K,V> {
    
Returns the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys.

Returns:
the comparator used to order the keys in this map, or null if this map uses the natural ordering of its keys
    Comparator<? super K> comparator();

    
Returns a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive. (If fromKey and toKey are equal, the returned map is empty.) The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside its range.

Parameters:
fromKey low endpoint (inclusive) of the keys in the returned map
toKey high endpoint (exclusive) of the keys in the returned map
Returns:
a view of the portion of this map whose keys range from fromKey, inclusive, to toKey, exclusive
Throws:
java.lang.ClassCastException if fromKey and toKey cannot be compared to one another using this map's comparator (or, if the map has no comparator, using natural ordering). Implementations may, but are not required to, throw this exception if fromKey or toKey cannot be compared to keys currently in the map.
java.lang.NullPointerException if fromKey or toKey is null and this map does not permit null keys
java.lang.IllegalArgumentException if fromKey is greater than toKey; or if this map itself has a restricted range, and fromKey or toKey lies outside the bounds of the range
    SortedMap<K,V> subMap(K fromKey, K toKey);

    
Returns a view of the portion of this map whose keys are strictly less than toKey. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside its range.

Parameters:
toKey high endpoint (exclusive) of the keys in the returned map
Returns:
a view of the portion of this map whose keys are strictly less than toKey
Throws:
java.lang.ClassCastException if toKey is not compatible with this map's comparator (or, if the map has no comparator, if toKey does not implement java.lang.Comparable). Implementations may, but are not required to, throw this exception if toKey cannot be compared to keys currently in the map.
java.lang.NullPointerException if toKey is null and this map does not permit null keys
java.lang.IllegalArgumentException if this map itself has a restricted range, and toKey lies outside the bounds of the range
    SortedMap<K,V> headMap(K toKey);

    
Returns a view of the portion of this map whose keys are greater than or equal to fromKey. The returned map is backed by this map, so changes in the returned map are reflected in this map, and vice-versa. The returned map supports all optional map operations that this map supports.

The returned map will throw an IllegalArgumentException on an attempt to insert a key outside its range.

Parameters:
fromKey low endpoint (inclusive) of the keys in the returned map
Returns:
a view of the portion of this map whose keys are greater than or equal to fromKey
Throws:
java.lang.ClassCastException if fromKey is not compatible with this map's comparator (or, if the map has no comparator, if fromKey does not implement java.lang.Comparable). Implementations may, but are not required to, throw this exception if fromKey cannot be compared to keys currently in the map.
java.lang.NullPointerException if fromKey is null and this map does not permit null keys
java.lang.IllegalArgumentException if this map itself has a restricted range, and fromKey lies outside the bounds of the range
    SortedMap<K,V> tailMap(K fromKey);

    
Returns the first (lowest) key currently in this map.

Returns:
the first (lowest) key currently in this map
Throws:
NoSuchElementException if this map is empty
    K firstKey();

    
Returns the last (highest) key currently in this map.

Returns:
the last (highest) key currently in this map
Throws:
NoSuchElementException if this map is empty
    K lastKey();

    
Returns a Set view of the keys contained in this map. The set's iterator returns the keys in ascending order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations. It does not support the add or addAll operations.

Returns:
a set view of the keys contained in this map, sorted in ascending order
    Set<K> keySet();

    
Returns a Collection view of the values contained in this map. The collection's iterator returns the values in ascending order of the corresponding keys. The collection is backed by the map, so changes to the map are reflected in the collection, and vice-versa. If the map is modified while an iteration over the collection is in progress (except through the iterator's own remove operation), the results of the iteration are undefined. The collection supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Collection.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Returns:
a collection view of the values contained in this map, sorted in ascending key order
    Collection<V> values();

    
Returns a Set view of the mappings contained in this map. The set's iterator returns the entries in ascending key order. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. If the map is modified while an iteration over the set is in progress (except through the iterator's own remove operation, or through the setValue operation on a map entry returned by the iterator) the results of the iteration are undefined. The set supports element removal, which removes the corresponding mapping from the map, via the Iterator.remove, Set.remove, removeAll, retainAll and clear operations. It does not support the add or addAll operations.

Returns:
a set view of the mappings contained in this map, sorted in ascending key order
    Set<Map.Entry<K, V>> entrySet();
New to GrepCode? Check out our FAQ X