Question

I have list of key and value pair in that i need one item to come in front. Eg :100 different type of fruits and fruitcode, i will sort alphabetically and put in JSON, i need to bring orange to be front so the order will be Orage,Apple,Banana .. etc. Is this possible

Iterator itr = treeMap.entrySet().iterator();
            while ( itr.hasNext() )
            {
                Map.Entry me = (Map.Entry) itr.next();
                String fruit_type="Orange";
                 if(fruit_type.equals(me.getValue())){
                     itr.remove();
                    }
                JSONObject frtObj = new JSONObject();

                frtObj.put("fruitCode", me.getValue());
                frtObj.put("fruitName", me.getKey());
                frtArrayObj.add(frtObj);
Was it helpful?

Solution

You can not just put some entry as first entry in treemap. There is another way way to achieve it, while creating the TreeMap pass custom Comaparator.

And in the Comparator<? super K> comparator write a logic that Orange should come in first element. It ensure you that "Orange" would be always first element of the map.

Code snippet :

Comparator<String> customComparator = new Comparator<String>() {
        @Override public int compare(String s1, String s2) {
            // Add null check
            if(s1.equals("Orange"))
               return 1; 
            else if(s2.equals("Orange"))
               return -1;
            return s1.compareTo(s2);
        }           
    };

...

SortedMap<String,String> map = new TreeMap<String,String>(customComparator );
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top