【java8】语法对比

map foreach

以前的方式

for (Map.Entry<String, String> map : paramsMap.entrySet()) {
params.add(new BasicNameValuePair(map.getKey(), map.getValue()));
}

java8

paramsMap.forEach((key,value) -> params.add(new BasicNameValuePair(key,value)));

List foreach

以前方式

for (String item:arrayList){
    System.out.println(item);
}

java8

list.forEach(item->System.out.println(item));

list.forEach(System.out::println);

list.forEach(item->{
    if("zhangshan".equals(item)){
        System.out.println(item);
    }
});

list.stream()
        .filter(s-> s.contains("li")||s.contains("si"))
        .forEach(System.out::println);

list.stream()
        .filter(s->s.contains("E"))
        .findFirst().ifPresent(s -> System.out.println(s));

【例1】select d.name from dish d where d.price > 20
java8之前的写法

List dishes = new ArrayList();
for(DishInfo dish : dishes){
    if(dish.getPrice() > 20){
        dishes.add(dish);
    }
}

java8

List dishes = Lists.newArrayList(
new DishInfo("chiken", (float) 10.0,DishInfo.Type.OTHER),
new DishInfo("beef",(float) 25.0,DishInfo.Type.BEAF)
);

List dishNames = 
             dishes.stream()
           //dishes.parallelStream() //并行处理
                   .filter(dish -> dish.getPrice() > 20)                                  
                   .sorted(comparing(DishInfo::getType))
                   .map(DishInfo::getName)  
                   .limit(3)                                    
                   .collect(toList());

//.count()
//.distinct()
//.skip(2)
//.map(String::length)
//.flatMap()
//.reduce()
Stream.iterate()
Stream.generate(Math::random).limit(6).forEach(System.out::println);

List<String> title = Arrays.asList("java","python","javascript");
        Stream<String> streamTitle = title.stream();
        streamTitle.forEach(System.out::println);

你可能感兴趣的:(Java核心基础)