Monday 8 February 2016

Sort an ArrayList with another using Java


Sort an ArrayList with another ArrayList


This java sample helps you to understand how you can sort an ArrayList with another ArrayList.

Step 1: 
Create class SampleSort. Follow below program.

package com.sample;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author Vimal Sanker
 *
 */
public class SampleSort {

public static void main(String[] args) {
                List<String> listA = java.util.Arrays.asList("Monday","Thursday","Sunday","Tuesday","Saturday","Wednesday","Friday");
                List<String> listB = java.util.Arrays.asList("Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday");
                Map<String, Integer> day = new HashMap<String, Integer>();
                for(int i=0;i<listB.size();i++) {
                        String day2 = listB.get(i);
                        day.put(day2, i);
                }
                Collections.sort(listA, new CustomFieldComparator(day));
                for(String s : listA) {
                        System.out.println(s);
                }
        }
}

Above program have two ArrayList, listA and listB. Here we are trying to sort listA with listB.


Step 2:
Create class CustomFieldComparator. Follow below program.

package com.Sample;

import java.util.Comparator;
import java.util.Map;

/**
 * 
 * @author Vimal Sanker
 *
 */
public class CustomFieldComparator implements Comparator<String> {
        private Map<String, Integer> sortOrder;
        public CustomFieldComparator(Map<String, Integer> sortOrder) {
                this.sortOrder = sortOrder;
        }
        public int compare(String il, String i2) {
                Integer weekdayPos1 = sortOrder.get(il.trim());
                if (weekdayPos1 == null) {
                        throw new IllegalArgumentException("Bad name encountered: "+ il);
                }
                Integer weekdayPos2 = sortOrder.get(i2);
                if (weekdayPos2 == null) {
                        throw new IllegalArgumentException("Bad name encountered: "+ i2);
                }
                return weekdayPos1.compareTo(weekdayPos2);
         }
}

This is Comparator class which will help us to do the sorting. This is a custom class created as per the requirement.

Step 3:
Execute class SampleSort.

Output:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

............................................................................................................................................
Enjoy.....

No comments:

Post a Comment