java List 排序

这几天在做项目,有一个是需求就是对产品列表进行价格销量等排序,本来是用多种sql语句来实现,不过每次和数据库的交互都会耗费大量资源,而且我们的List的数据内容不变。

换一个思路,我们把产品列表读进内存,然后就可以对内存中的List排序。

 

这里用到的Collections里的sort方法,我们重新Comparator类

public class product

{

          public String name;

          public int price;

   

          public String getName()

          {

                 return this.name;

           }

          public void setName(String name)

          {

                 this.name = name;

          }

          public int getPrice()

          {

                 return this.price;

           }

          public void setPrice(int price)

          {

                 this.price = price;

          }    

}

 

public class PriceDescComparator implements Comparator

{

         public int compare(Object o1,Object o2)

         {

                product p1 = (product)o1;

                product p2 = (product)o2;

               

                return -(p1.getPrice - p2.getPrice);

         }

}

 

public class sort()

{

            public static void main(String[] args)

            {

                  List l = new ArrayList();

                  product p1 = new product();

                  product p2 = new product();

                  product p3 = new product();

   

                 p1.setName("p1");

                 p1.setPrice(100);

                

                p2.setName("p2");

                p2.setPrice(101);

 

                 p3.setName("p3");

                 p3.setPrice(99);

 

                 l.add(p1);

                 l.add(p2);

                 l.add(p3);

                 Collections.sort(l,new PriceDescComparator());

 

                Iterator it = l.iterator();

                while(it.hasNext())

                {

                        product p = (product)it.next();

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

                 }

             }

}

 

 这时的结果是   p2,p1,p3

 

你可能感兴趣的:(java,sql)