Java8新特性----數組,流

數組聲明

List<Integer>  list =Arrays.asList(1,4,7,9,3,1);

遍歷數組

Arrays.asList( "a", "e", "d" ).forEach(e -> System.out.println( e ) );

須要更復雜的語句塊,則可使用花括號將該語句塊括起來java

Arrays.asList( "a", "b", "d" ).forEach( e -> {
            System.out.print( e );
            System.out.print( e );
        } );

排序

Collections.sort(list, (s1, s2) -> s1.compareTo(s2));

 

Stream

過濾filter

List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd", "", "jkl");
 List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());

forEach

 'forEach' 來迭代流中的每一個數據數組

map

map 方法用於映射每一個元素到對應的結果dom

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
// 獲取對應的平方數
List<Integer> squaresList = numbers.stream().map( i -> i*i).distinct().collect(Collectors.toList());

limit

limit 方法用於獲取指定數量的流spa

Random random = new Random();
random.ints().limit(10).forEach(System.out::println);

sorted

sorted 方法用於對流進行排序code

Random random = new Random();
random.ints().limit(10).sorted().forEach(System.out::println);

Collectors

Collectors 類實現了不少歸約操做,例如將流轉換成集合和聚合元素。Collectors 可用於返回列表或字符串排序

List<String>strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
List<String> filtered = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.toList());
 
System.out.println("篩選列表: " + filtered);
String mergedString = strings.stream().filter(string -> !string.isEmpty()).collect(Collectors.joining(", "));
System.out.println("合併字符串: " + mergedString);

 

IntSummaryStatistics(求最大、最小、總量、計數)

List<Integer> numbers = Arrays.asList(3, 2, 2, 3, 7, 3, 5);
 
IntSummaryStatistics stats = integers.stream().mapToInt((x) -> x).summaryStatistics();
 
System.out.println("列表中最大的數 : " + stats.getMax());
System.out.println("列表中最小的數 : " + stats.getMin());
System.out.println("全部數之和 : " + stats.getSum());
System.out.println("平均數 : " + stats.getAverage());
相關文章
相關標籤/搜索