1.filter the files and get hidden files;
File[] hiddenFiles = new File(".").listFiles(new FileFilter(){
public boolean accept(File file){
return file.isHidden()
}
})
use java8’s :: syntax –>take a function as a parameter and pass it to listFiles
File[] hiddenFiles = new File(".").listFiles(File::isHidden)
2.lambda demo–>filter apples
write a function :
public static void main( String[] args ) {
System.out.println( "Hello World!" );
List<Apple> inventory= Arrays.asList(new Apple(10,"red"),new Apple(100,"green"),
new Apple(200,"red"));
//这个App::isReaApple代表App类里的方法isReaApple
// List<Apple> redApples=filterApple(inventory,App::isReaApple);
//如果不想写方法则用下面方式 lambda
List<Apple> redApples=filterApple(inventory,(Apple a)->"red".equals(a.getColor()) || a.getWeight()<100);
System.out.println(redApples);
}
static List<Apple> filterApple(List<Apple> inventory, Predicate<Apple> p){
List<Apple> result=new ArrayList<>();
for(Apple apple : inventory){
if(p.test(apple)){
result.add(apple);
}
}
return result;
}
public static boolean isReaApple(Apple a){
return "red".equals(a.getColor());
}
on the above code ,Predicate is a interface from java.util.function
notice: lambda needs a function interface which is defined as a interface that only have a abstract function.
There are some functional interfaces in package java.util.function
inventory.sort(comparing((a) -> a.getWeight()))
inventory.sort(comparing(Apple::getWeight));
comparing is from java.util.Comparator.comparing
the method is called method references.
inventory.sort(comparing(Apple::getWeight)
.reversed()
.thenComparing(Apple::getCountry));
//这个是比较器链
//comparing()返回的是Comparator<>对象
3.Common functional Interfaces
(1) java.util.function.Predicate<T>
be used to filter and get data.
public interface Predicate<T>{
boolean test(T t);
}
(2)java.util.function.Consumer<T>
if you want to operation Object T, you can use it. the function has no return value.
public interface Consumer<T>{
void accept(T t);
}
(3)java.util.function.Function<T, R>
be used to get object’s information such as array.length , object’s property and son on.
public interface Function<T, R>{
R apply(T t);
}
notice: Because they are all generic, if we use Primitive data like int , double , ‘int’ will be automatically transfered to ‘Integer’( called autoboxing
). if this, java
performance will be consumed. so there are some interfaces for this problem.
DoublePredicate 、 IntConsumer 、 LongBinaryOperator 、 IntFunction ToIntFunction<T> 、 IntToDoubleFunction
4.use stream
Q: get some characters that differ from each other from a word Array. For example [“Hello”,”World”], you want to return a list that is [“H”,”e”,”l”, “o”,”W”,”r”,”d”].
a wrong solution: words.stream().map(word -> word.split("")).distinct().collect(toList());
cause the parameter is a Array.
right solution: use flatMap
1.transfer the array to a character stream.
String[] arrayOfWords = {"Goodbye", "World"};
Stream<String> streamOfwords = Arrays.stream(arrayOfWords);
2.use flatMap
to make every value from the stream become a another stream and connect .
List<String> uniqueCharacters =
words.stream()
.map(w -> w.split(""))
.flatMap(Arrays::stream)
.distinct()
.collect(Collectors.toList());
5.Optional ——-common tool class
instantiate Optional class methods:
- Optional optCar =Optional.empty() —-> a null optional instance
- Optional optCar = Optional.of(car)–>Optional.of()
- Optional optCar = Optional.ofNullable(car); –>allow null value
example:
public String getCarInsuranceName(Optional<Person> person) {
return person.flatMap(Person::getCar)
.flatMap(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");
} //faltMap防止嵌套,出现两层Optional Person::getCar get Optional<Car>
notice: Optional class has no Serializable
interface. so if your class wants to be serialized, supply a variable value that can be accessed and it’s type is Optional
example:
public class Person {
private Car car;
public Optional<Car> getCarAsOptional() {
return Optional.ofNullable(car);
}
}
encapsulation map.
example:
Object value = map.get("key");
Optional<Object> value = Optional.ofNullable(map.get("key"));
string can be transfered to integer.
example:
public static Optional<Integer> stringToInt(String s) {
try {
return Optional.of(Integer.parseInt(s));
} catch (NumberFormatException e) {
return Optional.empty();//否则返回一个空的 Optional 对象
}
}
/*Optional 也 提 供 了 类 似 的 基 础 类
型—— OptionalInt 、 OptionalLong 以及 OptionalDouble ——所以方法可
以不返回 Optional<Integer> ,而是直接返回一个 OptionalInt 类型的对象*/
simplify code
example:
public int readDuration(Properties props, String name) {
String value = props.getProperty(name);
if (value != null) {
try {
int i = Integer.parseInt(value);
if (i > 0) {//检查返回的数
return i;//字是否为正数
}
} catch (NumberFormatException nfe) { }
}
//如果前述的条件都不满足,返回0
return 0;
}
change it ;
public int readDuration(Properties props, String name) {
return Optional.ofNullable(props.getProperty(name))
.flatMap(OptionalUtility::stringToInt)
.filter(i -> i > 0)
.orElse(0);
}