Who?
@carimatics --Web application engineer ――I'm being played with Perl in business --Emacs Lisp I'm getting tired of Gonyo and crying I'm using Vim --Uncle Garupan --Now I'm living just to see the movie version released in December
--Syntax for writing anonymous functions easily --Improved readability --Internally a functional interface --The only interface that should be implemented
Stream API --Applying lambda expressions to 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
――It's just 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();
}
;
--The interface name to be implemented is self-explanatory --Funtion is written on the left side
Function<String, Integer> countLen =
(String s) {
return s.length();
}
;
--The return value is self-explanatory --Integer is written on the left side --Method name is self-explanatory --Since there is only one method to implement
Function<String, Integer> countLen = (String s) { return s.length(); };
Organize
Function<String, Integer> countLen = (String s) -> { return s.length(); };
--Lambda expressions require a ->
(arrow token) between the argument and the body
Function<String, Integer> countLen = (String s) -> s.length() ;
--If the body is a single sentence, you can omit return
and curly braces.
Function<String, Integer> countLen = s -> s.length() ;
--Can be omitted if the argument type is known --String is written on the left side
Function<String, Integer> countLen = s -> s.length();
Organize (Although it can be changed to the method reference format, it is omitted due to time constraints)
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) //30s
.filter(e -> e.getGender() == Gender.MALE) //male
.mapToInt(e -> e.getSalary()) //Salary
.average() //average
.orElse(0.0); //0 if there is no applicable person.0
--Can be written concisely --Improved readability --Easy to maintain
The Stream API function has been added to Java9 as well, which is very convenient!
Recommended Posts