Java8实战Chap4&5流处理

Stream

可以看做是遍历数据集的高级迭代器。

先定义一个DISH类,任务是要求返回低热量的菜的名称。(卡路里<400)

package lambdasinaction.chap4;
import java.util.*;

public class Dish {

    private final String name;
    private final boolean vegetarian;
    private final int calories;
    private final Type type;

    public Dish(String name, boolean vegetarian, int calories, Type type) {
        this.name = name;
        this.vegetarian = vegetarian;
        this.calories = calories;
        this.type = type;
    }

    public String getName() {
        return name;
    }

    public boolean isVegetarian() {
        return vegetarian;
    }

    public int getCalories() {
        return calories;
    }

    public Type getType() {
        return type;
    }

    public enum Type { MEAT, FISH, OTHER }

    @Override
    public String toString() {
        return name;
    }

    public static final List<Dish> menu =
            Arrays.asList( new Dish("pork", false, 800, Dish.Type.MEAT),
                           new Dish("beef", false, 700, Dish.Type.MEAT),
                           new Dish("chicken", false, 400, Dish.Type.MEAT),
                           new Dish("french fries", true, 530, Dish.Type.OTHER),
                           new Dish("rice", true, 350, Dish.Type.OTHER),
                           new Dish("season fruit", true, 120, Dish.Type.OTHER),
                           new Dish("pizza", true, 550, Dish.Type.OTHER),
                           new Dish("prawns", false, 400, Dish.Type.FISH),
                           new Dish("salmon", false, 450, Dish.Type.FISH));
}

这是不用流的写法

 public static void main(String [] args) throws Exception{

        List<Dish> dishList = new ArrayList<Dish>();

        for(Dish dish:menu){
            if(dish.getCalories()<400){
                dishList.add(dish);
            }
        }

        Collections.sort(dishList, new Comparator<Dish>() {
            @Override
            public int compare(Dish dish1, Dish dish2) {
                return Integer.compare(dish1.getCalories(),dish2.getCalories());
            }
        });

        List<String> result = new ArrayList<String>();
        for(Dish dish:dishList){
            result.add(dish.getName());
        }
        System.out.println(result);
    }

如果使用流的话,上述代码实际上在完成四个步骤:
1.过滤(选出cal<500)
2.排序
3.得到菜名
4.转换成list

 List<String> lowCalResult = menu.parallelStream()
                .filter(t->t.getCalories()<500)
                .sorted(Comparator.comparing(Dish::getCalories))//sort by cal
                .map(Dish::getName)
                .collect(Collectors.toList());
        System.out.println(lowCalResult);
 //按照种类分别把菜名分到不同的list
        Map<Dish.Type,List<Dish>> dishedByType =
                menu.stream().collect(groupingBy(Dish::getType));           

stream一些特点
只能遍历一次:

当遍历到第二次的时候:

Exception in thread “main” java.lang.IllegalStateException: stream has already been operated upon or closed

会抛出异常。

外部迭代与内部迭代

集合遍历是属于外部迭代,相当于把迭代的过程暴露给用户,而内部迭代已经封装好了。(collect方法)

流操作

在这里插入图片描述
关闭流的操作(eg:collect)叫做终端操作。

中间的操作看似是独立的,但实际上可以合并起来。

   List<String> lowCalResult = menu.parallelStream()
                .filter(t->{
                    System.out.println("filtering: "+t.getName());
                    return t.getCalories()>300; })
                .map(d->{
                    System.out.println("mapping: "+d.getName());
                    return d.getName();
                })
                .limit(3)
                .collect(Collectors.toList());
        System.out.println(lowCalResult);

result:

filtering: chicken
filtering: rice
filtering: french fries
mapping: chicken
mapping: rice
mapping: french fries
filtering: pork
mapping: pork
filtering: pizza
filtering: prawns
filtering: salmon
mapping: prawns
filtering: season fruit
mapping: pizza
filtering: beef
mapping: salmon
mapping: beef
[pork, beef, chicken]

StreamAPI 的操作

在这里插入图片描述

流的用法

用谓词筛选
List<String> vege = menu.parallelStream()
                    .filter(Dish::isVegetarian)
                    .map(Dish::getName)
                    .collect(Collectors.toList());
        System.out.println(vege);
distinct
 List<Integer> nums = Arrays.asList(1,2,2,4,5,4,2,2);
        nums.stream().filter(i->i%2==0).distinct().forEach(System.out::println);
截短流

limit(n) 选出前n个
skip(n) 省略前n个

map

例如想返回每个菜名的长度

 menu.stream().map(Dish::getName).map(String::length).forEach(System.out::println);

flatMap

扁平流,把一个流中的每一个数值转换成另外一个流,然后把所有的流链接成为一个流。

 List<String> wordList = Arrays.asList("hello","world","byr");
        List<String> unique = wordList.stream()
                .map(w->w.split(""))
                .flatMap(Arrays::stream)
                .distinct()
                .collect(Collectors.toList());

        System.out.println(unique);

flatMap能够把map生成的所有的流汇聚成一条流

查找和匹配

检查谓词是否至少匹配一个元素
anymatch()

检查谓词是否匹配所有元素
allmatch()

确保没有元素与给定谓词匹配
noneMatch()

随便返回一个
findany()

会返回一个Optional,这是一个容器类,可以避免抛出null,因为findany可能会什么也找不到,返回一个Null

reduce 操作

遍历整个流然后返回一个值

List<Integer> nums = Arrays.asList(1,5,3,5,2,4);
        int product = nums.stream().reduce(0,(a,b)->(a+b));
        int product2 = nums.stream().reduce(0,Integer::sum);
        Optional<Integer> product3 = nums.stream().reduce(Integer::sum);
        System.out.println(product);
        System.out.println(product2);
        System.out.println(product3);

在这里插入图片描述

归约可以拿来求最大最小
  Optional<Integer> max = nums.stream().reduce(Integer::max);
   Optional<Integer> min = nums.stream().reduce(Integer::min);
map&reduce

用mapReduce来求和

  //统计流当中有多少菜
        int count = menu.stream()
                        .map(d->1)
                        .reduce(0,(a,b)->a+b);

数值流

Stream没有提供sum接口,但Java8引入了原始类型流特化,即IntStream,DoubleStream,LongStream,这些接口都有sum方法

1.映射到数值流

 int calories = menu.stream()
              .mapToInt(Dish::getCalories)
              .sum();
      System.out.println(calories);

2.转换为对象流

IntStream intStream  = menu.stream().mapToInt(Dish::getCalories);
      Stream<Integer>stream = intStream.boxed();

3.OptionalInt

mapToInt(可能处理的是空的流),默认返回0

数值范围

 IntStream evenNums = IntStream.rangeClosed(1,100)
                .filter(t->t%2==0);
        evenNums.forEach(System.out::println);
        

exam:构建一个三元数流

boxed方法可以显式地把特化的流转换回对象流
mapToObj(map方法同时转换回对象流)


        Stream<double[]> pythgoreanTriples =
                IntStream.rangeClosed(1,100).boxed()//change back to object stream
                .flatMap(a->
                        IntStream.rangeClosed(a,100)
                        .mapToObj(b->new double[]{a,b,Math.sqrt(a*a+b*b)})
                        .filter(t->t[2]%1==0));//change back to object stream

        pythgoreanTriples.limit(10)
                        .forEach(t->System.out.println(t[0]+" "+t[1]+" "+t[2]));
由文件生成流
  long uniqueWords = 0;
        try{
            Stream<String> lines = Files.lines(Paths.get("/home/graviti/下载/Java8InAction-master/src/main/resources/lambdasinaction/chap3/data.txt"), Charset.defaultCharset());
                uniqueWords = lines.flatMap(line -> Arrays.stream(line.split(" ")))
                                .distinct()
                                .count();
                System.out.println(uniqueWords);
        }catch (Exception e){
            e.printStackTrace();
        }
创建无限流
Stream.iterate

生成fibonachii 流

 Stream.iterate(new int []{0,1},t->(new int[]{t[1],t[0]+t[1]}))
               .limit(20)
               .map(t->t[0])
               .forEach(System.out::println);
以下是对提供的参考资料的总结,按照要求结构化多个要点分条输出: 4G/5G无线网络优化与网规案例分析: NSA站点下终端掉4G问题:部分用户反馈NSA终端频繁掉4G,主要因终端主动发起SCGfail导致。分析显示,在信号较好的环境下,终端可能因节能、过热保护等原因主动释放连接。解决方案建议终端侧进行分析处理,尝试关闭节电开关等。 RSSI算法识别天馈遮挡:通过计算RSSI平均值及差值识别天馈遮挡,差值大于3dB则认定有遮挡。不同设备分组规则不同,如64T和32T。此方法可有效帮助现场人员识别因环境变化引起的网络问题。 5G 160M组网小区CA不生效:某5G站点开启100M+60M CA功能后,测试发现UE无法正常使用CA功能。问题原因在于CA频点集标识配置错误,修正后测试正常。 5G网络优化与策略: CCE映射方式优化:针对诺基亚站点覆盖农村区域,通过优化CCE资源映射方式(交织、非交织),提升RRC连接建立成功率和无线接通率。非交织方式相比交织方式有显著提升。 5G AAU两扇区组网:与三扇区组网相比,AAU两扇区组网在RSRP、SINR、下载速率和上传速率上表现不同,需根据具体场景选择适合的组网方式。 5G语音解决方案:包括沿用4G语音解决方案、EPS Fallback方案和VoNR方案。不同方案适用于不同的5G组网策略,如NSA和SA,并影响语音连续性和网络覆盖。 4G网络优化与资源利用: 4G室分设备利旧:面对4G网络投资压减与资源需求矛盾,提出利旧多维度调优策略,包括资源整合、统筹调配既有资源,以满足新增需求和提质增效。 宏站RRU设备1托N射灯:针对5G深度覆盖需求,研究使用宏站AAU结合1托N射灯方案,快速便捷地开通5G站点,提升深度覆盖能力。 基站与程管理: 爱立信LTE基站邻区添加程:未提供具体内容,但通常涉及邻区规划、参数配置、测试验证等步骤,以确保基站间顺畅切换和覆盖连续性。 网络规划与策略: 新高铁跨海大桥覆盖方案试点:虽未提供详细内容,但可推测涉及高铁跨海大桥区域的4G/5G网络覆盖规划,需考虑信号穿透、移动性管理、网络容量等因素。 总结: 提供的参考资料涵盖了4G/5G无线网络优化、网规案例分析、网络优化策略、资源利用、基站管理等多个方面。 通过具体案例分析,展示了无线网络优化中的常见问题及解决方案,如NSA终端掉4G、RSSI识别天馈遮挡、CA不生效等。 强调了5G网络优化与策略的重要性,包括CCE映射方式优化、5G语音解决方案、AAU扇区组网选择等。 提出了4G网络优化与资源利用的策略,如室分设备利旧、宏站RRU设备1托N射灯等。 基站与程管理方面,提到了爱立信LTE基站邻区添加程,但未给出具体细节。 新高铁跨海大桥覆盖方案试点展示了特殊场景下的网络规划需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值