Re: Table object
Philipp wrote:
Hello,
I'm looking for a collection which behaves like a two column table
(ordered key - value pairs, key not unique). Is there such a thing
either in the JRE or Apache collections?
Hmm, the basic 2D table is called an array:
Type[][] table = ...;
The improved version of that is a List, typically an ArrayList:
ArrayList<type[]> table = ...;
Neither one is inherently sorted however. There are sort methods you
can call in Arrays and Collections
TreeMap seems like the closest match out of the older Java 5 collections:
TreeMap< Type1, Type2 > = ...;
But I think that's been gainsaid in this discussion already. There is
an IdentityHashMap, but that's unsorted. Bummer, it looks like you may
have to roll your own. Let's see how close I can get to what the other
posters did:
..... much later... OK I needed my IDE to finish this, and basically I
came up with a TreeMap too. The following code could stand to return
unmodifiable lists, as Lew pointed out. And I'm a little shaky on that
K extends Comparable... I think there should be a "? super" in there.
Have to give it some more thought. Seems to work ok though:
package fubar;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.TreeMap;
/**
*
* @author Brenden
*/
public class SortedMultiMap<K extends Comparable,V> extends
AbstractMap<K,List<V>> {
Map<K,List<V>> map = new TreeMap<K,List<V>>();
@Override
public Set<Entry<K, List<V>>> entrySet()
{
return map.entrySet();
}
@Override
public List<V> get( Object key )
{
return map.get( key );
}
public List<V> put( K key, V value )
{
List<V> exists = map.get( key );
if( exists != null ) {
exists.add( value );
} else {
exists = new ArrayList<V>();
exists.add( value );
map.put( key, exists );
}
return exists;
}
@Override
public List<V> remove( Object key )
{
return map.remove( key );
}
@Override
public String toString()
{
return map.toString();
}
public static void main( String[] args )
{
// test harness
SortedMultiMap<String,String> kills =
new SortedMultiMap<String,String>();
kills.put( "Blossuom", "Mojo Jojo");
kills.put( "Butercup", "Mojo Jojo");
kills.put( "Bubbles", "Gangreen Gang");
kills.put( "Butercup", "The Amoeba Boys");
kills.put( "Bubbles", "Sedusa");
kills.put( "Blossuom", "Fuzzy Lumpkins");
for( Entry<String,List<String>> e : kills.entrySet() ) {
System.out.println( e.getKey() + e.getValue() );
}
System.out.println( kills );
}
}