Java 8函数编程轻松入门(四)方法引用
C#中系统提供了许多IEnumerable的扩展方法。同样在Java 8中新引入了Collector类。
class Program
{
static void Main(string[] args)
{
Func<int, int, int> calc = Add;
}
public static int Add(int i, int j)
{
return i + j;
}
}
public class Chapter05 {
public static void main(String[] args) {
BinaryOperator<Integer> r = (x, y) -> x + y;
int result = r.apply(1, 2);
}
}
public class Chapter05 {
public static void main(String[] args) {
BinaryOperator<Integer> r = Chapter05::add;
int result = r.apply(1, 2);
}
public static Integer add(Integer i, Integer j) {
return i + j;
}
}
public static void main(String[] args) {
List<Integer> arrays = new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
add(4);
add(5);
}};
List<Integer> afterArrays = arrays.stream().filter(u -> u > 2).collect(Collectors.toList());
}
public static void main(String[] args) {
List<Integer> arrays = new ArrayList<Integer>() {{
add(1);
add(2);
add(3);
add(4);
add(5);
}};
Set<Integer> setArrays = arrays.stream().collect(Collectors.toSet());
}
Set<Integer> treesetArrays=arrays.stream().collect(Collectors.toCollection(TreeSet::new));
int max=treesetArrays.stream().max(Comparator.comparing(u->u)).get();
int collectMax=treesetArrays.stream().collect(Collectors.maxBy(Comparator.comparing(u->u))).get();
System.out.println("max:"+max);
System.out.println("CollectMax:"+collectMax);
int avg= treesetArrays.stream().collect(Collectors.averagingInt(u->u)).intValue();
System.out.println("Avg:"+avg);
public class Person {
public String name;
public int age;
public String sex;
public Person(){
}
public Person(String n,int a,String sex){
this.name=n;
this.age=a;
this.sex=sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
public class GroupByTest {
public static void main(String[] args){
List<Person> persons=new ArrayList<>();
persons.add(new Person("jack",23,"男"));
persons.add(new Person("Tom",20,"男"));
persons.add(new Person("Su",21,"女"));
persons.add(new Person("Lily",22,"女"));
Map<String,List<Person>> group=persons.stream().collect(Collectors.groupingBy(u->u.getSex()));
}
}
String str=persons.stream().map(u->u.getName()).collect(Collectors.joining(","));
//jack,Tom,Su,Lily
Java 8 可以使用computeIfAbsent缓存。
未使用computeIfAbsent
public class DetailsTest {
public static void main(String[] args){
Map<String,String> keyval=new HashMap<>();
String val=keyval.get("hello");
if(val==null){
keyval.put("hello","world");
}
System.out.print(keyval.get("hello"));
}
}
public class DetailsTest {
public static void main(String[] args){
Map<String,String> keyval=new HashMap<>();
keyval.computeIfAbsent("hello",u->keyval.put(u,"world"));
}
}
keyval.forEach((k,v)->{System.out.println("key:"+k+",value:"+v);});