欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java8新特性Stream流實(shí)例詳解

 更新時(shí)間:2017年10月25日 11:28:12   作者:我不是李大俠  
Stream流是數(shù)據(jù)渠道,用于操作數(shù)據(jù)源(集合、數(shù)組等)所生成的元素序列。這篇文章主要介紹了Java8新特性Stream流的相關(guān)資料,需要的朋友參考下吧

什么是Stream流?

Stream流是數(shù)據(jù)渠道,用于操作數(shù)據(jù)源(集合、數(shù)組等)所生成的元素序列。

Stream的優(yōu)點(diǎn):聲明性,可復(fù)合,可并行。這三個(gè)特性使得stream操作更簡(jiǎn)潔,更靈活,更高效。

Stream的操作有兩個(gè)特點(diǎn):可以多個(gè)操作鏈接起來(lái)運(yùn)行,內(nèi)部迭代。

Stream可分為并行流與串行流,Stream API 可以聲明性地通過(guò) parallel() 與sequential() 在并行流與順序流之間進(jìn)行切換。串行流就不必再細(xì)說(shuō)了,并行流主要是為了為了適應(yīng)目前多核機(jī)器的時(shí)代,提高系統(tǒng)CPU、內(nèi)存的利用率,并行流就是把一個(gè)內(nèi)容分成多個(gè)數(shù)據(jù)塊,并用不同的線程分別處理每個(gè)數(shù)據(jù)塊的流。java1.8并行流使用的是fork/join框架,關(guān)于fork/join框架可參考http://ifeve.com/talk-concurrency-forkjoin/學(xué)習(xí)。

注意 :

* 1、Stream不會(huì)自己存儲(chǔ)數(shù)據(jù)。

* 2、Stream不會(huì)改變?cè)瓕?duì)象,他們會(huì)返回一個(gè)新的Stream。

* 3、Stream操作是延遲的,他們會(huì)等到需要的結(jié)果時(shí)才執(zhí)行。

* 4、使用并行流并不一定會(huì)提高效率,因?yàn)閖vm對(duì)數(shù)據(jù)進(jìn)行切片和切換線程也是需要時(shí)間的。

本文主要講 Stream的3個(gè)操作步驟:1、創(chuàng)建Stream 2、中間操作3、終止操作。

創(chuàng)建Stream

創(chuàng)建Stream,就是將一個(gè)數(shù)據(jù)源 (如:集合、數(shù)組)轉(zhuǎn)化為一個(gè)流。

1、通過(guò)Collection系列提供的stream()(串行) 或parallelStream()(并行)獲取數(shù)據(jù)流。

2、通過(guò)Arrays中的靜態(tài)方法stream() 獲取數(shù)據(jù)流。

3、通過(guò)Stream類中的靜態(tài)方法of()獲取數(shù)據(jù)流。

 //1、通過(guò)Collection系列提供的stream()(串行) 或parallelStream()(并行)獲取
    List<String> list = new ArrayList<>();
    Stream<String> stream1 = list.stream();//串行流
    Stream<String> stream2 = list.parallelStream();//并行流
  //2、通過(guò)Arrays中的靜態(tài)方法stream() 獲取數(shù)據(jù)流
    User[] u = new User[2];
    Stream<User> stream3 = Arrays.stream(u);
  //3、通過(guò)Stream;類中的靜態(tài)方法of()
    Stream<String> stream4 = Stream.of("11","2");

中間操作

中間操作,即對(duì)數(shù)據(jù)源進(jìn)行一系列的操作處理。
多個(gè)中間操作可以連接起來(lái)性格一條流水線,除非流水線上觸發(fā)器終止操作,否則中間操作不會(huì)執(zhí)行任何的處理,而是在終止操作時(shí)一次性全部處理,成為惰性求值。

篩選和切片

1、filter(predicate)-接收l(shuí)ambda,從流中排除某些元素。

2、limit(n)-截?cái)嗔?,使其元素不超過(guò)給定數(shù)量。

3、skip(n)-跳過(guò)元素,返回一個(gè)扔掉了前n個(gè)元素的流。若流中元素不足n個(gè),則返回一個(gè)空流,與limit(n)互補(bǔ)。

4、distinct-篩選,通過(guò)流所生成元素的hashcode()和equals()去重復(fù)元素。

/**
   * 打印年齡大于18的前4位用戶信息(不重復(fù))
   * 并跳過(guò)第1個(gè)用戶
   */
@Test
  public void test1(){
    list.stream()
    .filter((x)->x.getAge()>18)
    .distinct()
    .limit(4)
    .skip(1).forEach(System.out::println);
  }

映射

1、map,接收Lambda,將元素轉(zhuǎn)換成其他形式或提取信息。接收一個(gè)函數(shù)作為參數(shù),該函數(shù)會(huì)被應(yīng)用到每一個(gè)元素上,并將其映射成一個(gè)新的元素。

2、mapToDouble/mapToInt/mapToLong,接收一個(gè)函數(shù)作為參數(shù),該函數(shù)會(huì)被應(yīng)用到每個(gè)元素上,產(chǎn)生一個(gè)新的DoubleStream/IntStream/LongStream。

3 、flatMap,接收一個(gè)函數(shù)作為參數(shù),將流中的每個(gè)值都換成一個(gè)流,然后把流連接成一個(gè)流。

 @Test
  public void test2(){
    ///map
    list.stream().map(User::getName)
    .forEach(System.out::println);
    //flatMap
    List<List<User>> list1 = new ArrayList<>();
    list1.add(list);
    list1.stream().flatMap(Stream::getNames)
    .forEach(System.out::println);
  }
  public static Stream<String> getNames(List<User> list){
    List<String> list1 = new ArrayList<String>();
    for (User user : list) {
      list1.add(user.getName());
    }
    return list1.stream();
  }

排序

1、sorted(),產(chǎn)生一個(gè)新流,其中按自然順序排序。

2、sorted(Comparator),產(chǎn)生一個(gè)新流,其中按比較器順序排序。

@Test
  public void test3(){
    List<String> list =Arrays.asList("aa","bb","cc","dd");
    list.stream().sorted()
    .forEach(System.out::println);
    //
    list.stream().sorted((x,y) -> {
      if(x.equals(y)){
        return 1;
      }else{
        return -1;
      }
    } ).forEach(System.out::println);
  }

終止操作

終止操作是執(zhí)行中間操作鏈,并產(chǎn)生結(jié)果(一個(gè)新流),數(shù)據(jù)源本身并不受影響,其結(jié)果可以是任何不是流的值。

查找與匹配

1、allMatch,檢查是否匹配所有元素。
2、anyMatch,檢查是否至少匹配一個(gè)元素。
3、noneMatch,檢查是否沒(méi)有匹配所有元素。
4、findFirst,返回第一個(gè)元素。
5、findAny,返回當(dāng)前流中的任意元素。
6、count,返回流中元素的總數(shù)。
7、 max,返回流中最大值。
8、min,返回流中最小值。
9、froEach(Consumer c) 內(nèi)部迭代。

@Test
  public void test4(){
    boolean b = list.stream().
        noneMatch((e) ->
        e.getName().equals("zhao"));
    System.out.println(b);
    Optional<User> op = list.parallelStream()
        .filter((x) -> x.getAge() == 18)
        .findAny();
    System.out.println(op.get());
  }

歸約

reduce,可以將流中的值反復(fù)結(jié)合起來(lái),得到一個(gè)值。

@Test
  public void test5(){
    //轉(zhuǎn)List
    List<String> list1 =list.stream()
        .map(User::getName)
        .collect(Collectors.toList()) ;
    list1.forEach(System.out::println);
    //轉(zhuǎn)HashSet
    HashSet<String> set = list.stream().
        map(User::getName)
        .collect(Collectors.toCollection(HashSet::new));
    set.forEach(System.out::println);
    //總數(shù)
    Long count = list.stream()
        .collect(Collectors.counting());
    System.out.println(count);
    //平均年齡
    double avAge = list.stream()
        .collect(Collectors.averagingInt(User::getAge));
    System.out.println(avAge); 
    //總年齡
    int toAge = list.stream()
        .collect(Collectors.summingInt(User::getAge));
    System.out.println(toAge);
    //最大值
    Optional<User> u = list.stream()
        .collect(Collectors.maxBy((e1,e2) 
            -> Integer.compare(e1.getAge(),e2.getAge() )));
    System.out.println(u);
    //平均年齡
    IntSummaryStatistics collect = list.stream()
        .collect(Collectors.summarizingInt(User::getAge));
    System.out.println(collect.getAverage());
    //分組
    Map<Integer, List<User>> l= list.stream()
        .collect(Collectors.groupingBy(User::getAge));
    System.out.println(l);
    //多級(jí)分組
    Map<Integer,Map<String,List<User>> > ls= list.stream()
        .collect(Collectors.groupingBy(
            User::getAge,Collectors.groupingBy(User::getSex)));
    System.out.println(ls);
    //分區(qū)
    Map<Boolean,List<User>> map= list.stream()
        .collect(Collectors.partitioningBy((x) 
            -> x.getAge()>18));
    System.out.println(map);
    //連接字符串
    String str = list.stream().map(User::getName)
        .collect(Collectors.joining(",","-","-"));
    System.out.println(str);
  }

總結(jié)

以上所述是小編給大家介紹的Java8新特性Stream流實(shí)例詳解,希望對(duì)大家有所幫助,如果大家有任何疑問(wèn)請(qǐng)給我留言,小編會(huì)及時(shí)回復(fù)大家的。在此也非常感謝大家對(duì)腳本之家網(wǎng)站的支持!

相關(guān)文章

最新評(píng)論