ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Object List groupping and sorted by fields
    Tech/SpringBoot 2019. 1. 9. 11:33
    반응형



    public class Country {

    // 출력 순서
    private int display;
    // 국가 이름
    private String name;
    }

    국가 리스트를 출력 순서를 우선으로 정렬 후 국가이름으로 정렬 하도록 한다. 

    - display 가 동일한 그룹을 맵으로 만들도록 한다.

    - 키값에 해당하는 리스트를 이름순으로 정렬한다.

    public List<Country> sortedByDisplayAndName(List<Country> countryList){
    Map<Integer,List<Country>> map = new TreeMap<>();
    for (Country m: countryList) {
    int key = m.getDisplay();
    if(map.containsKey(key)){
    List<Country> list = map.get(key);
    list.add(m);
    }else{
    List<Country> list = new ArrayList<>();
    list.add(m);
    map.put(key,list);
    }
    }
    List<Country> resultList = new ArrayList<>();
    //TreeMap 은 기본적으로 키값 오름차순 정렬
    Iterator<Integer> iterators = map.keySet().iterator();
    while (iterators.hasNext()){
    List<Country> tmpList = map.get(iterators.next());
    Collections.sort(tmpList, new Comparator<Country>() {
    @Override
    public int compare(Country o1, Country o2) {
    return o1.getName().compareToIgnoreCase(o2.getName());
    }
    });
    resultList.addAll(tmpList);
    }
    return resultList;
    }


    테스트


    @Test
    public void sortedByuDisplayAndNameTest() {
    List<Country> countryList = Arrays.asList(
    new Country(4,"China"),
    new Country(9999,"Bangladesh"),
    new Country(1,"Korea"),
    new Country(3,"Russia"),
    new Country(3,"Thailand"),
    new Country(9999,"Canada"),
    new Country(9999,"India"),
    new Country(9999,"Nepal"),
    new Country(2,"Usa"),
    new Country(2,"Uzbekistan"));
    System.out.println("Before::::" + countryList);
    System.out.println("After::::" + sortedByDisplayAndName(countryList));
    }


    결과


    Before::::[Country{display=4, name='China'}, Country{display=9999, name='Bangladesh'}, Country{display=1, name='Korea'}, Country{display=3, name='Russia'}, Country{display=3, name='Thailand'}, Country{display=9999, name='Canada'}, Country{display=9999, name='India'}, Country{display=9999, name='Nepal'}, Country{display=2, name='Usa'}, Country{display=2, name='Uzbekistan'}]
    After::::[Country{display=1, name='Korea'}, Country{display=2, name='Usa'}, Country{display=2, name='Uzbekistan'}, Country{display=3, name='Russia'}, Country{display=3, name='Thailand'}, Country{display=4, name='China'}, Country{display=9999, name='Bangladesh'}, Country{display=9999, name='Canada'}, Country{display=9999, name='India'}, Country{display=9999, name='Nepal'}]


    반응형
Designed by Tistory.