Who?
@carimatics
--Syntaxe pour écrire facilement des fonctions anonymes
Stream API --Application d'expressions lambda aux collections - filter - map - reduce
etc...
Function<String, Integer> countLen = new Function<>() {
@Override
public Integer apply(String s) {
return s.length();
}
};
int len = countLen.apply("Function class sample!!!");
System.out.println(len); // => 24
――C'est juste long
Function<String, Integer> countLen = new Function<>() {
@Override
public Integer apply(String s) {
return s.length();
}
};
Function<String, Integer> countLen =
@Override
public Integer apply(String s) {
return s.length();
}
;
Function<String, Integer> countLen =
(String s) {
return s.length();
}
;
Function<String, Integer> countLen = (String s) { return s.length(); };
Organiser
Function<String, Integer> countLen = (String s) -> { return s.length(); };
Les expressions --Lambda nécessitent ->
(jeton de flèche) entre l'argument et le corps
Function<String, Integer> countLen = (String s) -> s.length() ;
Function<String, Integer> countLen = s -> s.length() ;
--Peut être omis si le type d'argument est connu --La chaîne est écrite sur le côté gauche
Function<String, Integer> countLen = s -> s.length();
Organiser (Bien qu'il puisse être changé au format de référence de méthode, il est omis en raison de contraintes de temps)
Function<String, Integer> countLen = new Function<>() {
@Override
public Integer apply(String s) {
return s.length();
}
};
Function<String, Integer> countLen = s -> s.length();
Stream API
double sum = 0.0;
for (int i = 1; i <= 100; i++) {
sum += i;
}
double ave = sum / 100;
Stream API
double ave = IntStream.rangeClosed(1, 100)
.average()
.orElse(0.0);
double sumSalary = 0.0;
for (Employee employee : employees) {
if (30 <= employee.getAge() && employee.getAge() < 40
&& employee.getGender() == Gender.MALE) {
sumSalary += employee.getSalary();
}
}
double a = employees.isEmpty() ? 0.0 : sumSalary / employees.size();
Stream API
double averageSalary =
employees.stream()
.filter(e -> 30 <= e.getAge() && e.getAge() < 40) //30 s
.filter(e -> e.getGender() == Gender.MALE) //Masculin
.mapToInt(e -> e.getSalary()) //Un salaire
.average() //moyenne
.orElse(0.0); //0 s'il n'y a pas de personne applicable.0
--Peut être rédigé de manière concise
La fonction Stream API a également été ajoutée à Java9, ce qui est très pratique!
Recommended Posts