반응형
https://www.daleseo.com/java-comparable-comparator/
ProductTest product1 = new ProductTest();
product1.setId(444);
product1.setName("zzz1");
product1.setRemain(3);
product1.setPrice(5555);
product1.setCreateDate(null);
product1.setUpdateDate(null);
ProductTest product2 = new ProductTest();
product2.setId(555);
product2.setName("zzz2");
product2.setRemain(4);
product2.setPrice(3333);
product2.setCreateDate(null);
product2.setUpdateDate(null);
ProductTest product3 = new ProductTest();
product3.setId(666);
product3.setName("zzz3");
product3.setRemain(5);
product3.setPrice(4444);
product3.setCreateDate(null);
product3.setUpdateDate(null);
List<ProductTest> products = Arrays.asList(product1, product2, product3);
System.out.println(products.get(0).getName());
System.out.println(products.get(1).getName());
System.out.println(products.get(2).getName());
System.out.println("================================");
// 객체정렬은 Comparator 사용
Collections.sort(products, (a, b) -> a.getPrice() - b.getPrice()); // 오름차순 (작은거부터)
Collections.sort(products, (a, b) -> b.getPrice() - a.getPrice()); // 내림차순 (큰거부터)
System.out.println(products.get(0).getName());
System.out.println(products.get(1).getName());
System.out.println(products.get(2).getName());
반응형