Sort objects in list in Java

Source: Internet
Author: 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 = 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); // collect by the number of clicks in reverse order. 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 ;}}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.