0 votes
in JAVA by
How to sort Collection in Java 8?

1 Answer

0 votes
by
Prior to Java 8:
//Older way to sort, before java 8
		noteLst.sort(new Comparator<Notes>() {
		@Override
		public int compare(Notes n1, Notes n2) {
			return n1.getId()-n2.getId();
		}
	});	
In Java 8:
public class TestNotes {

    public static void main(String[] args) {

        List<Notes> noteLst = new ArrayList<>();
        noteLst.add(new Notes(1, "aa", 11));
        noteLst.add(new Notes(3, "cc", 33));
        noteLst.add(new Notes(4, "bb", 44));
		noteLst.add(new Notes(2, "dd", 34));
        noteLst.add(new Notes(5, "zz", 32));

		// java 8 sort according to id 1,2,3,4,5
        noteLst.sort((n1, n2)->n1.getId()-n2.getId());

		//java 8 print the notes using lamda
		noteLst.forEach((note)->System.out.println(note));
    }
}
//Output 

Notes [id=1, tagName=aa, tagId=11]
Notes [id=2, tagName=dd, tagId=34]
Notes [id=3, tagName=cc, tagId=33]
Notes [id=4, tagName=bb, tagId=44]
Notes [id=5, tagName=zz, tagId=32]

...