java中對List中對象排序實現

來源:互聯網
上載者:User
package com.test;import java.util.ArrayList;import java.util.Collections;import java.util.Comparator;import java.util.List;public class NewsManager {/** * @param args */public static void main(String[] args) {List newss=getNewsList();for(int i=0;i<newss.size();i++){News news=(News)newss.get(i);System.out.println("id:"+news.getId());System.out.println("title:"+news.getTitle());System.out.println("hits:"+news.getHits());}}public static List getNewsList(){List list=new ArrayList();News news1=new News();news1.setHits(1);news1.setId(1);news1.setTitle("test1");list.add(news1);News news2=new News();news2.setHits(7);news2.setId(2);news2.setTitle("test2");list.add(news2);News news3=new News();news3.setHits(3);news3.setId(3);news3.setTitle("test3");list.add(news3);News news4=new News();news4.setHits(5);news4.setId(4);news4.setTitle("test4");list.add(news4);// 按點擊數倒序Collections.sort(list, new Comparator<News>() {public int compare(News arg0, News arg1) {int hits0 = arg0.getHits();int hits1 = arg1.getHits();if (hits1 > hits0) {return 1;} else if (hits1 == hits0) {return 0;} else {return -1;}}});return list;}}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.