This post will explain how to sort the list by name using Comparator and java 8 Stream.
usage of BiFunction
package com.siva; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.function.BiFunction; import java.util.stream.Stream; public class TestJava8Example { public static void main(String[] args) { //Usage of BiFunction BiFunctionadd = (a, b) -> a + b; System.out.println("Addition of two values["+add.apply(20, 30) +"]"); //usage of stream List arrayList = new ArrayList (); Person p = new Person(); p.setName("siva"); p.setAge(32); arrayList.add(p); Person p1 = new Person(); p1.setName("kumar"); p1.setAge(33); arrayList.add(p1); Person p2 = new Person(); p2.setName("raju"); p2.setAge(33); arrayList.add(p2); Person p3 = new Person(); p3.setName("jatin"); p3.setAge(2); arrayList.add(p3); Stream stream = arrayList.stream(); stream.forEach(x -> System.out.println("Name: [" + x.getName()+"] Age ["+x.getAge()+"]")); //Sort By name Using comparator Comparator byPersonName = (Person p4, Person p5) -> p4.getName().compareTo( p5.getName()); Stream sorted = arrayList.stream().sorted(byPersonName); sorted.forEach(e -> System.out.println("sorted Name: [" + e.getName()+"] Age ["+e.getAge()+"]")); } }
output
Addition of two values[50] Name: [siva] Age [32] Name: [kumar] Age [33] Name: [raju] Age [33] Name: [jatin] Age [2] sorted Name: [jatin] Age [2] sorted Name: [kumar] Age [33] sorted Name: [raju] Age [33] sorted Name: [siva] Age [32]
No comments:
Post a Comment