foreword
The article was first published on the public account (Moon with Flying Fish), and then synchronized to the personal website: xiaoflyfish.cn/
I feel that I have gained something, I hope to help you like it, forward it, thank you, thank you
In our daily work, Lambda uses a lot of scenarios, that is, the Lambda stream operation under the collection class, often a few lines of code can help us implement complex code
Next, we will explain the common method use cases of Lambda streams.
ForEach
Collection traversal forEach method
public void testForEach(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
list.forEach(s-> System.out.println(s));
}
复制代码
Collect
Convert the manipulated object into a new object
public void testCollect(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("2");
}};
//转换为新的list
List newList = list.stream().map(s -> Integer.valueOf(s)).collect(Collectors.toList());
}
复制代码
Filter
Filter means to filter, as long as the data that satisfies the Filter expression can be left, and the unsatisfied data is filtered out
public void testFilter() {
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
list.stream()
// 过滤掉我们希望留下来的值
// 表示我们希望字符串是 1 能留下来
// 其他的过滤掉
.filter(str -> "1".equals(str))
.collect(Collectors.toList());
}
复制代码
Map
The map method allows us to perform some stream transformations. For example, the element in the original stream is A. Through the map operation, the element in the returned stream can be B.
public void testMap() {
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
//通过 map 方法list中元素转化成 小写
List<String> strLowerList = list.stream()
.map(str -> str.toLowerCase())
.collect(Collectors.toList());
}
复制代码
MapToInt
The function of the mapToInt method is the same as that of the map method, except that the result returned by mapToInt has no generic type, and it is already a stream of int type. The source code is as follows:
public void testMapToInt() {
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
list.stream()
.mapToInt(s->Integer.valueOf(s))
// 一定要有 mapToObj,因为 mapToInt 返回的是 IntStream,因为已经确定是 int 类型了
// 所有没有泛型的,而 Collectors.toList() 强制要求有泛型的流,所以需要使用 mapToObj
// 方法返回有泛型的流
.mapToObj(s->s)
.collect(Collectors.toList());
list.stream()
.mapToDouble(s->Double.valueOf(s))
// DoubleStream/IntStream 有许多 sum(求和)、min(求最小值)、max(求最大值)、average(求平均值)等方法
.sum();
}
复制代码
Distinct
The distinct method has the function of deduplication
public void testDistinct(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("2");
}};
list.stream()
.map(s -> Integer.valueOf(s))
.distinct()
.collect(Collectors.toList());
}
复制代码
Sorted
The Sorted method provides sorting and allows us to customize the sorting
public void testSorted(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
list.stream()
.map(s -> Integer.valueOf(s))
// 等同于 .sorted(Comparator.naturalOrder()) 自然排序
.sorted()
.collect(Collectors.toList());
// 自定义排序器
list.stream()
.map(s -> Integer.valueOf(s))
// 反自然排序
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
}
复制代码
groupingBy
groupingBy is able to group according to fields, toMap is to convert the data format of List into the format of Map
public void testGroupBy(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("2");
}};
Map<String, List<String>> strList = list.stream().collect(Collectors.groupingBy(s -> {
if("2".equals(s)) {
return "2";
}else {
return "1";
}
}));
}
复制代码
FindFirst
findFirst means that the first value that satisfies the condition is matched and returned
public void testFindFirst(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("2");
}};
list.stream()
.filter(s->"2".equals(s))
.findFirst()
.get();
// 防止空指针
list.stream()
.filter(s->"2".equals(s))
.findFirst()
// orElse 表示如果 findFirst 返回 null 的话,就返回 orElse 里的内容
.orElse("3");
Optional<String> str= list.stream()
.filter(s->"2".equals(s))
.findFirst();
// isPresent 为 true 的话,表示 value != null
if(str.isPresent()){
return;
}
}
复制代码
Reduce
The reduce method allows us to stack computed values inside a loop
public void testReduce(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
list.stream()
.map(s -> Integer.valueOf(s))
// s1 和 s2 表示循环中的前后两个数
.reduce((s1,s2) -> s1+s2)
.orElse(0);
list.stream()
.map(s -> Integer.valueOf(s))
// 第一个参数表示基数,会从 100 开始加
.reduce(100,(s1,s2) -> s1+s2);
}
复制代码
Peek
The peek method is very simple, we do anything in the peek method that has no return value, such as printing logs
public void testPeek(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
list.stream().map(s -> Integer.valueOf(s))
.peek(s -> System.out.println(s))
.collect(Collectors.toList());
}
复制代码
Limit
The limit method will limit the number of output values, and the input parameter is the size of the limit
public void testLimit(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("3");
}};
list.stream()
.map(s -> Integer.valueOf(s))
.limit(2L)
.collect(Collectors.toList());
}
复制代码
Max , Min
Through the max and min methods, you can get the largest and smallest objects in the collection
public void testMaxMin(){
List<String> list = new ArrayList<String>() {{
add("1");
add("2");
add("2");
}};
list.stream().max(Comparator.comparing(s -> Integer.valueOf(s))).get();
list.stream().min(Comparator.comparing(s -> Integer.valueOf(s))).get();
}
复制代码
Summarize
In this article, we introduce more than a dozen commonly used methods of lambda expressions
Knowing these, you will definitely be handy when you encounter complex data structure transformation at work.
At last
Welcome to pay attention to the public number: moon with flying fish
Share a practical technical article every day, which is helpful for interviews and work
If you feel rewarded, remember to like, forward, share, thank you