当前位置:网站首页>[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
*/边栏推荐
- 华为设备配置BGP AS号替换
- Socket model of punctual atom stm32f429 core board
- Redis core configuration and advanced data types
- 用游戏来讲序列化与反序列化机制
- For cross-border e-commerce, the bidding strategy focusing more on revenue - Google SEM
- Two months' experience in C language
- Raspberry pie get temperature and send pictures to email
- Player actual combat 12 QT playing audio
- Mobileone: the mobile terminal only needs 1ms of high-performance backbone. You deserve it!
- C語言中主函數調用另外一個函數,匯編代碼理解
猜你喜欢

Mobileone: the mobile terminal only needs 1ms of high-performance backbone. You deserve it!

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

What is automatic bidding? What are its advantages?

Player practice 17 xvideowidget

In C language, the main function calls another function, which is understood by assembly code
![[ROC] aspriseocr C # English, Digital identification (not Chinese)](/img/80/198145df663d2eeec6b8b1d7bc47b6.png)
[ROC] aspriseocr C # English, Digital identification (not Chinese)
![JS (I) error [err\u module\u not\u found]: cannot find package 'UUID' imported](/img/a4/ef2d73576e027a2179ec9251167fa4.jpg)
JS (I) error [err\u module\u not\u found]: cannot find package 'UUID' imported

Huawei equipment is configured with H virtual private network
![[wechat applet] 5 Applet structure directory](/img/d6/4796c8b8fe482b261c5a1fbf79ba2b.jpg)
[wechat applet] 5 Applet structure directory

Perfect ending | detailed explanation of the implementation principle of go Distributed Link Tracking
随机推荐
En langage C, la fonction principale appelle une autre fonction et assemble le Code pour comprendre
Why do Chinese programmers change jobs?
[wechat applet] 4 Introduction to wechat developer tools
ADB control installation simulator
Junit多线程的写法
C secret arts script Chapter 2 (detailed explanation of pointers) (Section 3)
Solve the problem that IEEE latex template cannot display Chinese
Player actual combat 21 audio and video synchronization
If you want to build brand awareness, what bidding strategy can you choose?
Two methods of QT using threads
Basic usage of scanner
Software package for optimization scientific research field
ADB command (2) use monkey to test
C secret arts script Chapter 2 (detailed explanation of pointer) (Section 1)
【OCR】AspriseOCR C# 英文、數字識別(中文不行)
sql跨库注入
阿里建议所有 POJO 类属性使用包装类,但这些坑你有注意到吗?
And, or, not equal, operator
【Environment】1. Get the configuration in YML through the environment in the configuration class
[wechat applet] 6.1 applet configuration file