Take 2: Sorting maps in Java based on it’s values


In my old post Sorting maps in Java based on it’s values I wrote about a simple way to sort a Map object in Java based on the Map values, not the keys. That was back in good old Java pre-generics days. So how can you do the same with Java generics?

After a little fiddeling, here is how I ended up doing it:


import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;

public class MapValueSort {

    public static void main(String[] args) {

        Map<String, String> unsortedMap = new HashMap<String, String>();
        unsortedMap.put("2", "DEF");
        unsortedMap.put("3", "DEF");
        unsortedMap.put("1", "ABC");
        unsortedMap.put("5", "ZXY");
        unsortedMap.put("4", "BCD");

        printMap(unsortedMap);

        Map sortedMap = MapValueSort.sortMapByValue(unsortedMap);
       
        System.out.println();

        printMap(sortedMap);
    }

    /*
     * Util method that:
     * 1. Constructs a sorted map object providing a Comparator class
     * 2. Populating the sorted map by calling putAll with the UNsorted 
     *     data.
     * 3. When the putAll is called, the comparator is used to do the
     *     ordering.
     * 4. The method returns the sorted map.
     */
    static private <K, V extends Comparable<V>> Map<K, V> sortMapByValue(Map<K, V> unsortedMap) {
        SortedMap<K, V> sortedMap = new TreeMap<K, V>(new ValueComparer<K, V>(unsortedMap) );
        sortedMap.putAll(unsortedMap);
        return sortedMap;
    }

    /*
     * An inner class that implements a Comparator to compare the values inside the map.
     * Constructor takes the contentes of the UNsorted map.
     */
    private static class ValueComparer<K, V extends Comparable<V>> implements Comparator<K> {

        private final Map<K, V> map;

        public ValueComparer(Map<K, V> map) {
            super();
            this.map = map;
        }

        public int compare(K key1, K key2) {
            V value1 = this.map.get(key1);
            V value2 = this.map.get(key2);
            int c = value1.compareTo(value2);
            if (c != 0) {
                return c;
            }
            Integer hashCode1 = key1.hashCode();
            Integer hashCode2 = key2.hashCode();
            return hashCode1.compareTo(hashCode2);
        }
    }

    /*
     * Utility method to print a map using an Iterator.
     */
    private static void printMap(Map<?,?> data) {
        for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
            Object key = iter.next();
            System.out.println("Value/key:" + data.get(key).toString() + "/" + key.toString());
        }
    }
}

Advertisements

iPod video – first impressions

the iPod video (5th generation)So my old 4.th generation iPod finally stopped working a few weeks back. Actually it had stopped working before that, but after scanning the net for solutions I found a crazy-sounding advice to simpy hit my iPod in the back. But since I had nothing to loose I gave this low-tech solution a try, I wacked my iPod in the back, and behold, it worked again. But only for a while. Now it wont boot, wont mount in OSX, Linux og Windows XP. It have become slap-tolerant. The disk is definetely a goner.

I used my iPod every day from and to work and in many other situations. Music, audiobooks and podcast. Excellent to listen to in a cramped bus heading for Oslo in the early dark winter mornings. Reading is near to impossible and I had to resort to a lot of stearing. Stearing of a scenery I’ve seen thousands of times. Luckily my girldfriend recognized my dispair and got me a early birthdaypresent. (thats right people, im close to 31 years old on the 26th march, order gifts now!) – A sweet 30GB iPod video. It is probably not named “video”, but that makes it easier to identifiy.

My absolute first impression is that it a sleek, compact, thin, good-looking player.

Screen
Let me start off by saying I was a bit unsure about this LCD screen. What quality would it produce ? Would it be clear and produce enough contrast ? I downloaded a few video podcast and I must say the display impressed me. The picture was clear, detailed, sharp and with enough contrast to make for a nice videoplayer. I have only been able to test the video capability with slow moving elements and no action paced clips so I dont know have that would look. But for medium tempo video this handles that like a dream. However it suckes power out of the iPod pretty fast. I estimated about 60 minutes of watching before you empty a fresh charged battery. The iPod top layer seem to be made out of a transparent plastic-type material. And im not going to leave the house with the iPod not wrapped in the bundeled leather cover to protect the screen from scratches. The nano had some complaints about that. Wonder if it is the same type of material on these ?

Interface
Anyone familiar with the iPod interface would have no problems with this one. The only big difference that ive seen is the separation of the video- and music files. Interestingly enough, if you locate a video file from the music meny and try to play it, the iPod will play it without showing the actual video. Not quite sure if that is what I would like it to do but it might also become a neat feature. The interface is of course in color and showing any covers for music file that have that added. The screen also seem to be able to fit more lines of content into it. I havent been able to prove that though comparison to the 4.th generation, but it is my gut feeling. The well desined click wheel is made a little bit smaller but not improved on the things i miss. I never seem to get the proper sensitivity on it. Sometime i scroll really fast, sometimes really really slow.

Transfer of data
As mentioned, I got the 30GB model, and that is enough for me. Sure video will take more room than music but if you uncritically dump every mp3 you ever had and do not preserve space by choosing iTunes to only transfer the latest n-th podcast to you iPod, space would always be a problem. I was surprised to see that the firewire transfer was unsupported.

Overall
A great mp3/video player with the usual good looking Apple design and excellent video capabilities. I think I will use this until I have to bitch-slap in the back aswell 😉

Sorting maps in Java based on it’s values

Ever needed to sort a Map type collection in Java ?

Update: how do to this with generics?

Well i had to the other day and of course all the documentation pointed me in the direction of the SortedMap interface.

However, this datastructure is sorted on its keys and not on its values, which was really what I wanted to accomplish, so how do you do that? After a bit of fiddeling I found something that worked. Maybe its useful to you:

public class MapValueSort {
	
	/** inner class to do soring of the map **/
	private static class ValueComparer implements Comparator {
		private Map  _data = null;
		public ValueComparer (Map data){
			super();
			_data = data;
		}
		
         public int compare(Object o1, Object o2) {
        	 String e1 = (String) _data.get(o1);
             String e2 = (String) _data.get(o2);
             return e1.compareTo(e2);
         }
	}

	public static void main(String[] args){
		
		Map unsortedData = new HashMap();
		unsortedData.put("2", "DEF");
		unsortedData.put("1", "ABC");
		unsortedData.put("4", "ZXY");
		unsortedData.put("3", "BCD");
		
		
		SortedMap sortedData = new TreeMap(new MapValueSort.ValueComparer(unsortedData));
		
		printMap(unsortedData);
		
		sortedData.putAll(unsortedData);
		System.out.println();
		printMap(sortedData);
	}

	private static void printMap(Map data) {
		for (Iterator iter = data.keySet().iterator(); iter.hasNext();) {
			String key = (String) iter.next();
			System.out.println("Value/key:"+data.get(key)+"/"+key);
		}
	}
	
}

This should output something of the lines of:

Value/key:BCD/3
Value/key:DEF/2
Value/key:ZXY/4
Value/key:ABC/1

Value/key:ABC/1
Value/key:BCD/3
Value/key:DEF/2
Value/key:ZXY/4

Where the bottom last four lines obviously is sorted on the map’s values and not it’s keys.

Image presentation using Macromedia Flash

Recently I’ve been looking around the net to find a good solutions for displaying some photos in a online gallery using a flash movie to do the job. There are some good reasons to do that.

  • Flash is good for presentation. It can offer nice looking transisions between images using different slide and/or fading techniques. Using flash you can avoid writing a buch of HTML/scripting to generate a nice looking gallery with intuitive navigational elements.
  • Flash scales images satisfactory. Using flash, your images can be scaled automatically to suit any browser setting. Doing this with server/client side with scripting could get messy
  • Images presented in a flash movie is harder to steal. Of course not impossible, but harder. You can also easily apply a watermark to all your images quite easily.
  • Flash enables asynchronous loading of images. Your page can get big and loading everything around the gallery for every image shown can slow the user experience down. Flash can load images without reloading the whole page. Its the same ideà as for AJAX.
  • Flash facilitates the creation of enhanced navigational GUI elements. In addition to the usual HTML elements such as text links, images and form widgets, theres basically no limitation for what can constitue a navigational element in flash. Beware though of too imaginative solutions.

Im not a Flash creator myself. I’ve played around with it, but some of the key concepts are lost on me. Stealing Using other peoples stuff is for that reason my only option. I have some requirements to a Flash image gallery movie:

  1. It must be customizable. I cannot use a “wedding” theme with my images when they are images of sharks. No sharks have been engaged in wedlock for a long time. It must be possible to change basic stuff as colors, paddings, positions og elements and so forth.
  2. It must read the images from an external file. Some require you to actually open the Flash movie in the Flash editing IDE. Thats not dynamic. I must be able to dynamically genenerate the image gallery.
  3. It should scale well. Websites vary in size. So the Flash gallery should adhere to me, not the other way around.

These are some of the best ones out there that I’ve been able to find. (in no particular order)

  • http://www.bananalbum.com/ – Nice featured. Customizable to a certain point. Preloads thumbnails and loads large version of images on the fly. Calls javascript functions for popups and so forth. Bad documentation though. There are some nice features that I only found mentioned in a forum and not on the official site. Some of the GUI elements (like the dragbar) looks not quite as good as it could. There are possible to download PHP and other scripts to handle upload, but prepare to do quite a bit of customization of those.
  • http://www.flashimagegallery.com/ – Super fast gallery. Nice navigational elements. Good looking loaders. Really good PHP scripts for administration of galleries. Really sad that it handles scaling badly. It just gets bigger, magnified. If you expand the flash so it would have room to display one more thumbnail it doesnt. It simply scales up the thumnails already there. Same goes for text. I really hope the developer fixes this at some stage. No obvious customization options either.
  • http://www.airtightinteractive.com/simpleviewer/ – Nice gallery. Very good customization options. Preloads images (the large ones). Nice fading transitions. Available PHP scripts were not satisfactory for me. However my first choice at the moment. Recommended. You can also use JAlbum as a GUI client (Java program, runs on all platforms) to create albums really quickly.