java8 -->streams

2018-09-21  本文已影响0人  机器不能学习

stream和io流没有什么关系。
它是操作管道获取source(从各种数据中获得比如array,list....)并处理数据

public class study1 {

private static class myRand implements Supplier{
    private int index=0;
    private Random random=new Random();
    
    @Override
    public Object get() {
        int num=random.nextInt(100);
        return String.valueOf(num);
    }
}




static class Person{
    private String name;
    public Person() {
        
    }
    public Person(String name) {
        this.name=name;
    }
    public void setName(String name) {
        this.name=name;
    }
    public String getName() {
        return name;
    }
    public int getage() {
        return Integer.parseInt(name);
    }
}
public static void main(String[] args) throws FileNotFoundException {
    //流的构造
    Stream stream=Stream.of("a","b");
    String [] arr=new String[] {"a","b"};
    stream=Stream.of(arr);
    stream=Arrays.stream(arr);
    List<String> list=Arrays.asList(arr);
    stream=list.stream();
    
    //数值流
    IntStream.of(new int[] {1,2,3,4,5}).forEach(System.out::println);
    IntStream.range(1,3).forEach(System.out::println);                      //1
    IntStream.rangeClosed(1, 3).forEach(System.out::println);               //2   1.2的区别在于,2是闭区间,所以会输出1.2.3,而2是开区间智慧输出1.2

    //流转化为其他类型
    Object[] arr2=stream.toArray(String[] :: new);
    Stream stream2=Stream.of(arr2);
    
    //List<String> list2=(List<String>) stream.collect(Collectors.toList());
    Stack stack=(Stack) stream2.collect(Collectors.toCollection(Stack::new));       //每个资源只能被利用一次
    //String str = stream2.collect(Collectors.joining()).toString();
    //Set set1 = (Set) stream2.collect(Collectors.toSet());
    
    
    //用map把list元素全变为大写
    List<String> wordList=new ArrayList<>();
    wordList.add("dasda");
    wordList.add(1,"aaa");
    List<String> list3=wordList.stream()
            .map(String::toUpperCase)
            .collect(Collectors.toList());  
    list3.stream().forEach(System.out::println);
    
    
    //一对多的map
    Stream<List<Integer>> stream3=Stream.of(
            Arrays.asList(1,2,3),
            Arrays.asList(4,5,6)
            );
    stream3.flatMap((chilelist)->chilelist.stream())                //如果使用map那么这一步得到的是两个stream,而flatMap会将其都合并成一个stream,那么现在的stream中全部都是数字
            .forEach(System.out::println);

    //过滤器filter
    Integer[] num= {1,2,3,4,5,6,7,8};
    Integer[] newnum=Stream.of(num)
            .filter(n -> n%5 == 0)
            .toArray(Integer[] :: new);
    Stream.of(newnum).forEach(System.out::println);
    
    //lines()只是针对bufferReader的,也就是针对文件的
    File file=new File("/home/yhw/eclipse-workspace/TheHolleWord/src/streams/words.txt");
    InputStream in=new FileInputStream(file);
    InputStreamReader reader=new InputStreamReader(in);
    BufferedReader b=new BufferedReader(reader);
    List<String> myList=b.lines()
        .flatMap(n -> Stream.of(n.split(" ")))                                      //这里的单位是行,因为没办法用StringTokenizer,所以只能对每一行分流
        .filter(n -> n.length()>0)
        .collect(Collectors.toList());
    myList.stream()
    .peek(e->System.out.println(e))                                                 //peek和forEach的区别是,peak操作不会被消费
    .forEach(System.out::println);
    
    String nu=null;
    Optional.ofNullable(nu).ifPresent(System.out::println);

    
    //reduce合并函数
    String concat = Stream.of("A","B","C").reduce("",String::concat);
    System.out.println(concat);
    double min=Stream.of(-1.5,-2.0,-3.0).reduce(Double.MIN_VALUE,Double::min);
    System.out.println(min);
    Integer sum=Stream.of(1,2,3,4,5,6).reduce(Integer::sum).get();
    System.out.println(sum);
    
    
    
    //limit指定只要前几个数,skip去掉前几个数,sorted进行排序
    List<Integer> list2=Arrays.asList(1,2,3,4,43,64,63,636,4,63,3,11);
    list2.stream()                                                      //list只能用list.stream建立流
    .limit(8)
    .skip(2)
    .sorted((a1,b1)-> b1.compareTo(a1))                                 //sort可以自定义
    .forEach(System.out::println);

    
    //distinct除去重复项,Match可以匹配到是否有该元素,其类还有NoneMatch,allMatch返回布尔值
    BufferedReader buf=new BufferedReader(new FileReader("/home/yhw/eclipse-workspace/TheHolleWord/src/streams/words.txt"));
    int longlen=buf.lines()
            .mapToInt(ak -> ak.length())                                //直接处理整行处理
            .max()
            .getAsInt();
    System.out.println(longlen);
        
    BufferedReader buff=new BufferedReader(new FileReader("/home/yhw/eclipse-workspace/TheHolleWord/src/streams/words.txt"));
    boolean n=buff.lines()
        .flatMap((mp) -> Stream.of(mp.split(" ")))                          //flatMap是将一行的单词切分后,变为了单词流,相当于一行变多个
        .filter(fi -> fi.length()>0)                                    
        .map(String::toLowerCase)
        .peek(wo -> System.out.println(wo))
        .distinct()
        .anyMatch(word -> word.equals("ages"));                             
    System.out.println(n);
            
    //自定义流:模拟生成随机数,一般用于自定义的数据类型
    List<Person> list4=(List<Person>) Stream.generate(new myRand()).
        limit(100).
        peek(p->new Person(String.valueOf(p)))
        .collect(Collectors.toList());
    
    
    //conllect归组
     Map<String, List<Person>> map=(Map<String, List<Person>>) Stream.generate(new myRand2()).
            limit(100).
            collect(Collectors.groupingBy(Person::getName));
            
    Iterator iterator=map.entrySet().iterator();                        //先转化为迭代器,那么返回的每个对象,就是一个key(String)对应一个value(List)
    while(iterator.hasNext()) {
        Map.Entry<String,List<Person>> pEntry=(Entry<String, List<Person>>) iterator.next();
        System.out.println(pEntry.getKey()+":"+pEntry.getValue().get(0));
    }
    
    List<Person> list5=new ArrayList<>();
    list5.add(new myRand2().get());
    list5.add(new myRand2().get());
    list5.add(new myRand2().get());
    list5.add(new myRand2().get());
    list5.add(new myRand2().get());
    
    /*Map<Boolean, List<Person>> children = Stream.generate(new myRand()).                                          //这个p就是object而不是Person
             limit(100).
             collect(Collectors.partitioningBy(p -> p.getAge() < 18));*/
    
    Map<Boolean,List<Person>>maps=list5.stream().collect(Collectors.partitioningBy(p->p.getage()<18));          //只有当有明确数据类型时,p才是确定的数据类型
    System.out.println(maps.get(true).size());
}

@SuppressWarnings("rawtypes")
private static class myRand2 implements Supplier{
    private int index=0;
    private Random random=new Random();
    
    @Override
    public Person get() {
        int num=random.nextInt(100);
        return new Person(String.valueOf(num));
    }
}

}
https://www.ibm.com/developerworks/cn/java/j-lo-java8streamapi/

上一篇下一篇

猜你喜欢

热点阅读