当前位置:网站首页>Interface fonctionnelle, référence de méthode, Widget de tri de liste implémenté par lambda
Interface fonctionnelle, référence de méthode, Widget de tri de liste implémenté par lambda
2022-07-04 16:12:00 【Fabricant de bogues humanoïdes 9527】
1.InJava8Une interface fonctionnelle a été introduite dansConsumerObjet de,L'objet peut passer la méthode comme paramètre.
À propos delambdaTutoriels pour
/** * Tri des collections */
@AllArgsConstructor
public class CollSort {
// Facteur de tri
private final Long order;
public final static CollSort DESC = new CollSort(-1L);
public final static CollSort ASC = new CollSort(1L);
// Trier par nombre
public <E> Collection<E> sort(Collection<E> collection, ProcessorNumber<E> getParam) {
return collection.stream()
.filter(Objects::nonNull)
.sorted((o1, o2) -> {
// Ici, la méthode abstraite entrante est exécutée,Et passer dans les paramètres requis par la méthode de fonction,
// getParam La valeur de retour de a été déterminée dans la méthode de fonction abstraite
long result = Long.parseLong(String.valueOf(getParam.accept(o1))) - Long.parseLong(String.valueOf(getParam.accept(o2)));
result = result * order; // Le coefficient de tri intervient
return result == 0 ? 0 : result < 0 ? -1 : 1;
})
.collect(Collectors.toList());
}
// Trier par heure
public <E> Collection<E> sort(Collection<E> collection, ProcessorDate<E> getParam) {
return collection.stream()
.filter(Objects::nonNull) // Filtrage de données invalide
.sorted((o1, o2) -> {
long t1 = getParam.accept(o1).getTime(); // Voici une méthode abstraite getParam La valeur de retour de a été déterminée dans la méthode de fonction abstraite
long t2 = getParam.accept(o2).getTime();
long result = t1 - t2;
result = result * order; // Le coefficient de tri intervient
return result == 0 ? 0 : result < 0 ? -1 : 1;
})
.collect(Collectors.toList());
}
}
@FunctionalInterface
interface ProcessorDate<E> {
/** * Méthode de fonction abstraite pour obtenir les propriétés temporelles de l'objet * * @param t Objet * @return Propriétés temporelles de l'objet */
Date accept(E t);
}
@FunctionalInterface
interface ProcessorNumber<E> {
/** * Méthode de fonction abstraite pour obtenir les propriétés numériques d'un objet * * @param t Objet * @return Propriétés numériques de l'objet */
Number accept(E t);
}
Utiliser
public static void main(String[] args) {
SortTest sortTest = new SortTest();
ArrayList<User> users = new ArrayList<>();
users.add(new User("zz", 14,new Date()));
users.add(new User("zz", 17,new Date(System.currentTimeMillis()+1000000)));
users.add(new User("zz", 11,new Date(System.currentTimeMillis()+4000000)));
users.add(new User("zz", 15,new Date(System.currentTimeMillis()+9000000)));
users.add(new User("zz", 21,new Date(System.currentTimeMillis()+8000000)));
users.add(new User("zz", 7,new Date(System.currentTimeMillis()+3000000)));
sortTest.test(users);
}
public void test(List<User> users) {
// Pour les appels de méthodes d'outils ordinaires , La différence est que les paramètres sont une méthode , Il est également possible de se référer directement à la méthode
Collection<User> ageSort = CollSort.ASC.sort(users, User::getAge);
System.out.println("Classement par âge=========================");
ageSort.forEach(System.out::println);
System.out.println(" Tri des anniversaires ======================");
Collection<User> timeSort = CollSort.DESC.sort(users, User::getBirthDay);
timeSort.forEach(System.out::println);
}
Effets
L'interface de fonction peut être étendue en fonction des besoins ,Attention requiseType de paramètre
EtType de valeur de retour
, La plupart du temps, il suffit de changer le type de valeur de retour ;
Le type de paramètre et le type de valeur de retour affectent les paramètres que cette méthode de fonction doit passer au moment de l'appel , Et les valeurs de réponse
边栏推荐
- 案例分享|金融业数据运营运维一体化建设
- Overview of convolutional neural network structure optimization
- Feature extraction and detection 15-akaze local matching
- 2022年九大CIO趨勢和優先事項
- Redis' optimistic lock and pessimistic lock for solving transaction conflicts
- Variable cannot have type 'void'
- 干货 | fMRI标准报告指南新鲜出炉啦,快来涨知识吧
- Unity脚本API—Time类
- 数据库函数的用法「建议收藏」
- Unity script API - component component
猜你喜欢
AI system content recommendation issue 24
这几年爆火的智能物联网(AIoT),到底前景如何?
Book of night sky 53 "stone soup" of Apache open source community
Interface test - knowledge points and common interview questions
Unity脚本生命周期 Day02
Weekly recruitment | senior DBA annual salary 49+, the more opportunities, the closer success!
Scientific research cartoon | what else to do after connecting with the subjects?
Unity脚本常用API Day03
What is the future of the booming intelligent Internet of things (aiot) in recent years?
Talking about Net core how to use efcore to inject multiple instances of a context annotation type for connecting to the master-slave database
随机推荐
Unity脚本常用API Day03
Summary of database 2
Using celery in projects
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
[hcie TAC] question 5 - 1
js平铺数据查找叶子节点
Proxifier global agent software, which provides cross platform port forwarding and agent functions
The 17 year growth route of Zhang Liang, an open source person, can only be adhered to if he loves it
华为云数据库DDS产品深度赋能
How was MP3 born?
干货 | fMRI标准报告指南新鲜出炉啦,快来涨知识吧
31年前的Beyond演唱会,是如何超清修复的?
Interpretation of the champion scheme of CVPR 2020 night target detection challenge
Unity预制件Prefab Day04
Explore mongodb - mongodb compass installation, configuration and usage introduction | mongodb GUI
Usage of database functions "recommended collection"
Salient map drawing based on OpenCV
Functional interface, method reference, list collection sorting gadget implemented by lambda
After the eruption of Tonga volcano, we analyzed the global volcanic distribution and found that the area with the most volcanoes is here!
PXE网络