티스토리 뷰

Java

Strategy Pattern - Comparator

techbard 2016.07.21 10:27

Strategy02.zip



# Item.java


public class Item {

    private String name;

    private int value;


    public Item(String name, int value) {

this.name = name;

this.value = value;

    }


    public int getValue() {

        return value;

    }


    public String getName() {

        return name;

    }

}



# Main.java


import java.util.ArrayList;

import java.util.Collections;

import java.util.Comparator;

import java.util.List;


public class Main {

    private static void printItems(List<Item> items) {

for (Item item : items) {

   System.out.println(item.getName());

}

    }


    public static void main(String[] args) {

Item i01 = new Item("alpha", 20);

Item i02 = new Item("beta", 30);

Item i03 = new Item("gamma", 10);


List<Item> items = new ArrayList<>();

items.add(i01);

items.add(i02);

items.add(i03);


System.out.println("Not sorted");

printItems(items);


System.out.println("\n");


Collections.sort(items, new Comparator<Item>() {


   @Override

   public int compare(Item o1, Item o2) {

if (o1.getValue() > o2.getValue())

   return 1;

else if (o1.getValue() < o2.getValue())

   return -1;

return 0;

   }

});


System.out.println("Sorted by value");

printItems(items);


System.out.println("\n");


Collections.sort(items, new Comparator<Item>() {


   @Override

   public int compare(Item o1, Item o2) {

return -o1.getName().compareTo(o2.getName());

   }

});


System.out.println("Sorted reverse order by name");

printItems(items);

    }

}



# 결과


Not sorted

alpha

beta

gamma



Sorted by value

gamma

alpha

beta



Sorted reverse order by value

gamma

beta

alpha


댓글
댓글쓰기 폼
공지사항
Total
394,932
Today
3
Yesterday
28
«   2018/11   »
        1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30  
글 보관함