Method References
Method References
return results;
}
// Method 1
// To half the variable
public static Integer doHalf(Integer x) {
return x / 2;
}
// Method 2
// Square up the integer number
public static Integer doSquare(Integer x) {
return x * x;
}
import java.io.*;
import java.util.*;
// Class 1
// Helper class
class Person {
// Constructor
this.age = age;
// Getter-setters
// Class 2
// Main class
// Method 1
return a.getName().compareTo(b.getName());
// Method 2
// Static method to compare with age
return a.getAge().compareTo(b.getAge());
// Method 3
// List of person
Collections.sort(personList, GFG::compareByName);
personList.stream()
.forEach(System.out::println);
Collections.sort(personList, GFG::compareByAge);
personList.stream()
.map(x -> x.getName())
.forEach(System.out::println);
Output:
Sort by name :
poonam
sachin
vicky
Sort by age :
sachin
vicky
poonam
import java.io.*;
import java.util.*;
// Class 1
// Helper class
class Person {
// Attributes of a person
// Constructor
this.name = name;
this.age = age;
}
// Getter-setter methods
// Class 2
// Helper class
// Comparator class
class ComparisonProvider {
// Method 1
return a.getName().compareTo(b.getName());
// Method 2
return a.getAge().compareTo(b.getAge());
// Class 3
// Main class
// List of person
// comparator methods
ComparisonProvider comparator
= new ComparisonProvider();
Collections.sort(personList,
comparator::compareByName);
// Using streams
personList.stream()
.forEach(System.out::println);
Collections.sort(personList,
comparator::compareByAge);
personList.stream()
.forEach(System.out::println);
Output:
Sort by name :
poonam
sachin
vicky
Sort by age :
sachin
vicky
poonam
import java.io.*;
import java.util.*;
// Main class
personList.add("vicky");
personList.add("poonam");
personList.add("sachin");
Collections.sort(personList,
String::compareToIgnoreCase);
personList.forEach(System.out::println);
Output:
poonam
sachin
vicky
import java.io.*;
import java.nio.charset.Charset;
import java.util.*;
import java.util.function.*;
class Person {
// Constructor
public Person()
// to name
this.name
= ran
.ints(97, 122 + 1)
.limit(7)
.collect(StringBuilder::new,
StringBuilder::appendCodePoint,
StringBuilder::append)
.toString();
return age;
return name;
getObjectList(int length,
Supplier<T> objectSupply)
list.add(objectSupply.get());
return list;
// reference
List<Person> personList
= getObjectList(5, Person::new);
personList.stream()
.forEach(System.out::println);
Output:
vzskgmu
iupltfx
kocsipj
lyvhxsp
hbdphyv