函数式:用Lambda表达式实现函数的方式
1 什么时候使用函数式编程?
1.1 集合的操作
1.1.1 转换
list set map之间转换
1.1.2 聚合操作
count:获取数据数量 max:获取按照规则约定的最大值 min:获取按照规则约定的最小值 avg:获取平均值
1.1.3 循环处理
foreach:对数据进行循环处理
1.1.4 转换为String
joining:字符串数据指定分隔符
1.1.5 分组
groupingBy:按照特定功能处理分组
1.1.6 获取数组
toArray:数据转换为Object数组
1.2 Stream的操作
1.2.1 过滤
filter:按照规则筛选数据 distinct:过滤掉相同的数据
1.2.2 转换
map:接收一个T,返回一个R flatMap:处理Stream嵌套问题
1.2.3 其他操作
skip:忽略前n条数据 limit:限制只需要前n条数据 sorted:将数据排序
1.3 Optional的操作
1.3.1 检测是否为空
isPresent:存在返回true isEmpty:为空返回true
1.3.2 条件运算
ifPresent:存在则执行
1.3.3 默认值
orElse:当Optional为空时的的默认值
1.3.4 获取值
get:不为空时,获取数据
1.3.5 过滤
filter:对数据进行过滤
1.4 函数接口
1.4.1 Predicate
有输入且输出为布尔值
1.4.2 Function
有输入且有输出
1.4.3 Supplier
有输出没有输入
1.4.4 Consumer
有输入且没有输出
1.4.5 Operator
输入和输出同一类型
1.4.6 Comparator
输入两个值且输出为布尔值
1.5 方法引用
1.5.1 构造函数引用
::new
1.5.2 静态方法的引用
Integer:: toString
1.5.3 实例方法引用
person:: getName
1.5.4 引用任意对象的方法
forEach(person:: getName)
1.6 lambda表达式使用
()输入参数->()返回值
2 集合操作示例
public class _03finalStream {
public static void main(String
[] args
) {
List
<Person> people
= Arrays
.asList(new Person("zhangsan", "男"),
new Person("lisi", "男"),
new Person("xiaohong", "女"));
people
.stream().count();
people
.stream().max(Comparator
.comparing(Person
::getWeight
));
people
.stream().forEach(System
.out
::println
);
people
.stream().allMatch(Person
::isMale
);
people
.stream().anyMatch(Person
::isMale
);
people
.stream().noneMatch(Person
::isMale
);
Person person
= people
.stream().findAny().get();
Person person1
= people
.stream().findFirst().get();
Object
[] peopleArray
= people
.stream().toArray();
Integer r1
= Stream
.of(1, 2, 3).reduce((a
, b
) -> a
+ b
).get();
Stream
<String> nameStream
= Stream
.of("zhangsan", "lisi");
List
<String> nameList
= nameStream
.collect(Collectors
.toList());
List
<Integer> numList
= Arrays
.asList(3, 2, 1, 4, 8, 6, 7);
Stream
<Integer> numStream
= numList
.stream();
numStream
.sorted(Comparator
.comparing(Integer
::intValue
)).forEach(System
.out
::println
);
IntSummaryStatistics numSummary
= numStream
.collect(Collectors
.summarizingInt(Integer
::intValue
));
System
.out
.println(numSummary
.getMax() + " " + numSummary
.getMin() + " " + numSummary
.getAverage() + " " + numSummary
.getCount());
Map
<Integer
, List
<Integer>> map
= numStream
.collect(Collectors
.groupingBy(Integer
::intValue
));
Map
<Integer, Integer> map1
= numStream
.collect(Collectors
.toMap(Function
.identity(), Integer
::intValue
));
}
}
3 Stream操作示例
public class _02IntermediateStream {
public static void main(String
[] args
) {
List
<Person> people
= Arrays
.asList(new Person("zhangsan", "男"),
new Person("lisi", "男"),
new Person("xiaohong", "女"));
people
.stream().filter(person
-> person
.getGender().equals("男"))
.forEach(person
-> System
.out
.println(person
));
people
.stream().filter(Person
::isMale
).forEach(System
.out
::println
);
people
.stream().distinct()
.forEach(System
.out
::println
);
people
.stream().distinct()
.filter(person
-> person
.getGender().equals("男"))
.forEach(System
.out
::println
);
Stream
<Integer> nameLength
= people
.stream()
.map(Person
::getName
)
.map(String
::length
);
List
<Person> people1
= Arrays
.asList(new Person("zhangsan", "man", 100));
List
<Person> people2
= Arrays
.asList(new Person("lisi", "woman", 200));
List
<List
<Person>> peopleList
= Arrays
.asList(people1
, people2
);
peopleList
.stream()
.map(Collection
::stream
)
.forEach(personStream
-> personStream
.forEach(System
.out
::println
));
peopleList
.stream()
.flatMap(Collection
::stream
)
.forEach(System
.out
::println
);
people1
.stream().skip(1).forEach(System
.out
::println
);
people1
.stream().limit(1).forEach(System
.out
::println
);
people1
.stream().sorted(Comparator
.comparing(Person
::getWeight
)).forEach(System
.out
::println
);
}
}
4 Optioanl操作示例
public class _01getOptional {
public static void main(String
[] args
) {
Optional
<Object> emptyOptional
= Optional
.empty();
Optional
<String> stringOptional
= Optional
.of("zhangsan");
String str1
= "zhangsan";
String str2
= null
;
Optional
<String> stringOptional1
= Optional
.ofNullable(str1
);
Optional
<String> nullOptional2
= Optional
.ofNullable(str2
);
System
.out
.println(stringOptional
.isPresent());
System
.out
.println(nullOptional2
.isPresent());
System
.out
.println(nullOptional2
.isEmpty());
stringOptional1
.ifPresent(System
.out
::println
);
nullOptional2
.orElse("lisi");
if (nullOptional2
.isPresent()) {
nullOptional2
.get();
}
nullOptional2
.filter(s
-> s
.equals("zhangsan")).isPresent();
String str2
= nullOptional2
.map(s
-> "map" + s
).get();
}
}
5 函数式接口
5.1 Predicate
public class _01Predicate {
public static void main(String
[] args
) {
IntPredicate greaterThan0
= i
-> i
> 0;
System
.out
.println(greaterThan0
.test(10));
IntPredicate negate
= greaterThan0
.negate();
System
.out
.println(negate
.test(10));
IntPredicate lessThan100
= i
-> i
<= 100;
IntPredicate and
= greaterThan0
.and(lessThan100
);
System
.out
.println(and
.test(10));
IntPredicate or
= greaterThan0
.or(lessThan100
);
System
.out
.println(or
.test(-100));
BiPredicate
<String,Integer> isLenThanGivenLen
= (str
, len
) -> str
.length() > len
;
System
.out
.println(isLenThanGivenLen
.test("123",3));
}
}
5.2 Function
public class _02Function {
public static void main(String
[] args
) {
Function
<String, Integer> lengthFunction
= str
-> str
.length();
System
.out
.println(lengthFunction
.apply("123"));
Function
<Integer, Integer> plusFunction
= x
-> x
+ x
;
Function
<Integer,Integer> multiFunction
= x
-> x
* x
;
Function
<Integer, Integer> andThen
= plusFunction
.andThen(multiFunction
);
System
.out
.println(andThen
.apply(2));
Function
<Integer, Integer> compose
= plusFunction
.compose(multiFunction
);
System
.out
.println(compose
.apply(2));
IntFunction
<Integer> intPlusFunction
= x
-> x
+ x
;
System
.out
.println(intPlusFunction
.apply(2));
ToIntFunction
<Integer> toIntPlusFunction
= x
-> x
+ x
;
System
.out
.println(toIntPlusFunction
.applyAsInt(2));
IntToLongFunction intToLongPlusFunction
= x
-> x
+ x
;
System
.out
.println(intToLongPlusFunction
.applyAsLong(2));
BiFunction
<String,String,Integer> biFunction
= (str1
, str2
) -> str1
.length() + str2
.length();
System
.out
.println(biFunction
.apply("123","456"));
}
}
5.3 Consumer
public class _03Consumer {
public static void main(String
[] args
) {
Consumer
<String> lengthConsumer
= str
-> System
.out
.println(str
.length());
lengthConsumer
.accept("123");
}
}
5.4 Supplier
public class _04Supplier {
public static void main(String
[] args
) {
Supplier
<Long> supplier
= () -> System
.currentTimeMillis();
System
.out
.println(supplier
.get());
}
}
5.5 Operator
public class _05Operator {
public static void main(String
[] args
) {
IntUnaryOperator operatorFunction
= x
-> x
+ x
;
System
.out
.println(operatorFunction
.applyAsInt(2));
}
}
5.6 Comparator
public class _06Comparator {
public static void main(String
[] args
) {
Comparator
<Integer> compareFunction
= (num1
, num2
) -> num1
.compareTo(num2
);
System
.out
.println(compareFunction
.compare(1,2));
}
}
6 方法引用
6.1 Constructor
public class _01Constructor {
public static void main(String
[] args
) {
Supplier
<Person> emptyConstructor
= Person
::new;
Person person
= emptyConstructor
.get();
person
.setName("zhangsan");
System
.out
.println(person
);
Function
<String, Person> nameConstructor
= Person
::new;
Person person1
= nameConstructor
.apply("zhangsan");
System
.out
.println(person1
);
BiFunction
<String, String, Person> nameAndGenderConstructor
= Person
::new;
Person person2
= nameAndGenderConstructor
.apply("zhangsan", "man");
System
.out
.println(person2
);
}
}
6.2 Static
public class _02Static {
public static void main(String
[] args
) {
IntFunction
<String> intToStringFunction
= Integer
::toString
;
System
.out
.println(intToStringFunction
.apply(123));
}
}
6.3 Instance
public class _03Instance {
public static void main(String
[] args
) {
Person person
= new Person("zhangsan", "man", 100);
Consumer
<String> walkConsumer
= person
::walk
;
walkConsumer
.accept("上海路");
}
}
6.4 AnyInstance
public class _04AnyInstance {
public static void main(String
[] args
) {
List
<Person> people
= Arrays
.asList(new Person("zhagnsan", "man", 123)
, new Person("lisi", "man", 456));
people
.forEach(Person
::sayName
);
}
}