brunch

You can make anything
by writing

C.S.Lewis

by 김선우 Jun 11. 2016

Comparator 연습

// TODO: 2016. 6. 11.
// 1. 칼로리 400 미만 저장 후 오름차순으로 정렬
// 2. 코드는 심플하게
// 3. Comparator 는 익명클래스로 간단하게


List<Menu> menus = new ArrayList<Menu>(
        Arrays.asList(
                new Menu("a", 200),
                new Menu("b", 190),
                new Menu("c", 300),
                new Menu("d", 500),
                new Menu("e", 330),
                new Menu("f", 600),
                new Menu("g", 280),
                new Menu("h", 460),
                new Menu("i", 510),
                new Menu("j", 450)
        )
);
List<Menu> lowCalorieMenus = new ArrayList<Menu>();
// 400 미만의 칼로리만 저장
for (Menu menu : menus) {
    if (menu.getCalorie() < 400)
        lowCalorieMenus.add(menu);
}

//Collections.sort(rowCalorie, Menu.ascendingCalorie);
Collections.sort(lowCalorieMenus, new Comparator<Menu>() {
    public int compare(Menu o1, Menu o2) {
        //ascending order
        return o1.getCalorie() > o2.getCalorie() ? 1 : -1;
        //descending order
        //return o1.getCalorie() > o2.getCalorie() ? -1 : 1;
    }
});
for (Menu menu : lowCalorieMenus) {
    System.out.println(menu.getCalorie());
}


작가의 이전글 String Pool

작품 선택

키워드 선택 0 / 3 0

댓글여부

afliean
브런치는 최신 브라우저에 최적화 되어있습니다. IE chrome safari