当前位置:网站首页>[lambda operation jcf]
[lambda operation jcf]
2022-06-12 14:37:00 【Understand the principle + good code skills】
1. from HashMap Filter out less than 4 Of (filter), The filtered element list is sorted from small to large (sorted)
Map<String, Integer> m = Maps.newHashMap();
m.put("1", 1);
m.put("6", 6);
m.put("2", 2);
m.put("4", 4);
m.put("5", 5);
List<String> list = m.keySet()
.stream()
.filter(k -> { // Filter qualified key list
Integer num = m.get(k);
return num != null && num < 4;
})
.sorted(Comparator.reverseOrder()) // Sort from large to small
.collect(Collectors.toList());
if (list.size() == 0) {
System.out.println("-1");
} else {
System.out.println(list.get(0));
}
/*
2
*/2. Will store User Of ArrayList Sort by age (Comparator.comparing)
User u1 = new User("jianan", 28);
User u2 = new User("jiajing", 20);
User u3 = new User("xx", 30);
User u4 = new User("aa", 18);
User u5 = new User("bb", 40);
List<User> list = Arrays.asList(u1, u2, u3, u4, u5);
Collections.sort(list, Comparator.comparing(User::getAge));
System.out.println(list);
/*
[User{name='aa', age=18}, User{name='jiajing', age=20}, User{name='jianan', age=28}, User{name='xx', age=30}, User{name='bb', age=40}]
*/3. According to a List, Inside is another List Merge into one big List(flatMap、map)
/**
* Get all the fighters sent by this player id Set
*
* @param role
* @return
*/
private Set<String> getHaveDispatchHeroIdSet(Role role) {
Map<String, RoleRewardTaskItem> allTaskItem = getAllTaskItem(role);
Set<String> heroIdSet = allTaskItem.values()
.stream()
// Yes List Again Stream, And then map Can achieve more than one List The merging of
.flatMap(c -> c.getHeroes().stream())
.map(c -> c.getId())
.collect(Collectors.toSet());
return heroIdSet;
}Another example
package org.example.testflatmap;
import com.google.common.collect.Lists;
import java.util.Arrays;
import java.util.Set;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
Integer[][] arr = {
{1, 2, 3}, {3, 4, 5, 6}, {3, 4, 5}};
Set<Integer> set = Arrays.stream(arr)
.flatMap(c -> Lists.newArrayList(c).stream())
.collect(Collectors.toSet());
System.out.println(set);
}
}
/*
[1, 2, 3, 4, 5, 6]
*/4. For a list , Pass in a filter rule (Predicate) Apply to Make your own screening rules The situation of , Such demand 1 yes : Sift out something equal to a certain quality . demand 2 Is to filter out a certain level , demand 3 yes : Filtered weight >30 Of .
and stream Of filter Is a definite rule , This allows you to customize a rule .
/**
* Select those who meet this level item Information
* @param level
* @return
*/
public static QuestLv getQuestLvConfig(int level) {
Optional<QuestLv> op = GameLogicHelper.getNumericByFilter(QuestLv.class, q -> q.level == level);
return op.get();
}
public static <T> Optional<T> getNumericByFilter(Class<T> clazz, Predicate<T> filter) {
// So it is very convenient to read the table
List<String> tags = NumericService.getNumericIdList(clazz);
for (String tag : tags) {
T obj = NumericService.getNumericById(clazz, tag);
if (filter.test(obj)) {
return Optional.ofNullable(obj);
}
}
return Optional.empty();
}
5.findAny( Under specified rules , Find one )
/**
note :
1.findAny Compared with findFirst, Yes Short circuit evaluation characteristics , Slightly higher performance
2. In parallel stream Next ,findAny The results that may be returned each time are different , Find one and stop , and findFirst It is the same every time
3. In serial mode ,findAny The return value is the same every time
*/
public class TestFindAny {
public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 1, 2, 3, 4, 5);
Integer ret = list.stream()
.filter(v -> v > 30)
.findAny()
.orElse(null);
System.out.println(ret);
}
}
/*
null
*/6.Consumer( There are multiple behaviors , In case of uncertain behavior , Parameterize behavior )
public class TestConsumer {
private static class Test {
public void f() {
System.out.println("f called!!!");
}
}
public static void handler(Test test, Consumer<Test> consumer) {
// stay test When the parameter has a value
//consumer Accept one lambda expression
Optional.ofNullable(test)
.ifPresent(t1 -> consumer.accept(t1));
}
public static void main(String[] args) {
Test t = new Test();
// Pay attention to the... Below 2 There are three parameters lambda expression
handler(t, test -> test.f()); // Equivalent to handler(t, T::f);
}
}
/*
f called!!!
*/7) Pass in a rule , And get the return value (Function)
public class TestConsumer {
private static class Test {
public int g() {
return 1;
}
}
public static void handler(Test test, Consumer<Test> consumer) {
// Execute a when there is a value consumer
Optional.ofNullable(test)
.ifPresent(t1 -> consumer.accept(t1));
}
public static void main(String[] args) {
// Equivalent to Function<Test, Integer> fun = Test::g;
Function<Test, Integer> fun = t-> t.g();
Integer g = fun.apply(new Test());
System.out.println(g);
}
}8) Store an instance of a class (Supplier)
class Test {
private int num = 1;
public int getNum() {
return num;
}
public void setNum(int num) {
this.num = num;
}
@Override
public String toString() {
return "Test{" +
"num=" + num +
'}';
}
}
public class TestSupplier {
public Supplier<Test> s = Test::new;
public static void main(String[] args) {
TestSupplier test = new TestSupplier();
Test t = test.s.get();
t.setNum(100);
System.out.println(t);
}
}
/*
Test{num=100}
*/9) Multiple sort
package org.example.testSort;
import com.google.common.collect.Lists;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main(String[] args) {
List<A> list = Lists.newArrayList(
new A(1, 2, 3),
new A(1, 3, 2),
new A(2, 3, 1),
new A(1, 10, 1),
new A(4, 1, 1),
new A(4, 1, 1),
new A(4, 2, 0),
new A(3, 100, 100)
);
// according to a,b,c In turn
// stay sort The last call reversed
list = list.stream()
.sorted(Comparator.comparingInt(A::getA).thenComparingInt(A::getB).thenComparingInt(A::getC).reversed())
.collect(Collectors.toList());
System.out.println(list);
}
}
@Data
@AllArgsConstructor
class A {
private int a;
private int b;
private int c;
}
/*
[A(a=4, b=2, c=0), A(a=4, b=1, c=1), A(a=4, b=1, c=1), A(a=3, b=100, c=100), A(a=2, b=3, c=1), A(a=1, b=10, c=1), A(a=1, b=3, c=2), A(a=1, b=2, c=3)]
*/10) Method reference XXX::onHumanDead
XXX.class
public onHumanDead(SceneRole killer){
}
XXX::onHumanDead
This looks like passing a parameter ,
however Function2{
void apply(T1 p1, T2 p2);
}
It looks like 2 Parameters , It is precisely because there is a need for XXX example , therefore this Namely apply The first parameter of .
11)BiPredicate Define a rule
package org.example.testBiPredicate;
import java.util.function.BiPredicate;
public class Main {
public static void main(String[] args) {
A a = new A();
a.setCheck(a::checkMethodImpl);
System.out.println(a.isOk(18, "jianan"));
System.out.println(a.isOk(18, "jianan1"));
}
private static class A {
/**
* The rules
*/
private BiPredicate<Integer, String> check;
public boolean isOk(Integer age, String s) {
return check != null && check.test(age, s);
}
public void setCheck(BiPredicate<Integer, String> check) {
this.check = check;
}
/**
* Specify the implementation that satisfies the rule
*
* @param age
* @param s
* @return
*/
public boolean checkMethodImpl(Integer age, String s) {
if (age == 18 && s.equals("jianan")) {
return true;
}
return false;
}
}
}
/*
true
false
*/边栏推荐
- 华为设备配置OSPF伪连接
- Junit多线程的写法
- 数据的收集
- Jetpack架构组件学习(3)——Activity Results API使用
- C语言中主函数调用另外一个函数,汇编代码理解
- jenkins的RPC测试项目
- Webdriver opens in full screen and a prompt "Chrome is under the control of automatic test software" appears in Chrome
- Player actual combat 12 QT playing audio
- C語言中主函數調用另外一個函數,匯編代碼理解
- [Writeup]BUU SQL COURSE1[入门级]
猜你喜欢

【OCR】AspriseOCR C# 英文、數字識別(中文不行)

C secret arts script Chapter 5 (paragraph) (Section 3)

Player actual combat 21 audio and video synchronization

Recursive summary of learning function

Introduction to QT reflection mechanism and signal slot mechanism

Why do Chinese programmers change jobs?

PMP敏捷知识点

华为设备配置BGP AS号替换

Soft test (VI) Chrome browser installation selenium IDE
![[OCR] aspriseocr C # English, number recognition (not Chinese)](/img/80/198145df663d2eeec6b8b1d7bc47b6.png)
[OCR] aspriseocr C # English, number recognition (not Chinese)
随机推荐
What is automatic bidding? What are its advantages?
Player practice 20 audio thread and video thread
Variable parameters
selenium进阶
If you want to build brand awareness, what bidding strategy can you choose?
Machine learning learning notes
Reverse the encryption parameters of a hot water software
Unit test (I) unit test with JUnit
Webdriver opens in full screen and a prompt "Chrome is under the control of automatic test software" appears in Chrome
用游戏来讲序列化与反序列化机制
C secret arts script Chapter 5 (structure) (Section 1)
selenium之元素定位
ADB control installation simulator
[ROC] aspriseocr C # English, Digital identification (not Chinese)
The original Xiaoyuan personal blog project that has been around for a month is open source (the blog has basic functions, including background management)
【OCR】AspriseOCR C# 英文、数字识别(中文不行)
Design of PLC intelligent slave station based on PROFIBUS DP protocol
Soft test (VI) Chrome browser installation selenium IDE
For cross-border e-commerce, the bidding strategy focusing more on revenue - Google SEM
PMP agile knowledge points