一、intstream.of
intstream.of方法可以用來創建一個由指定值組成的流。它可以接受任意數量的參數,最終會將它們組成一個流。以下為示例代碼:
IntStream intStream = IntStream.of(1, 2, 3, 4, 5); intStream.forEach(System.out::print); //輸出:12345
使用of方法,我們可以創建一個IntStream流,並將1到5這五個數字組成的流輸出。
在實際開發中,我們有時會需要將數組或集合轉換為流進行操作。這時,我們可以使用intstream.of方法對原數組或集合進行轉換:
int[] arr = new int[] {1, 2, 3, 4, 5}; IntStream intStream = Arrays.stream(arr); intStream.forEach(System.out::print); //輸出:12345
在這個例子中,我們通過Arrays.stream方法將數組arr轉化為IntStream流,並輸出了其中包含的每一個元素。
二、intstream下載
在Java 8中,intsteam已經內置在了標準庫Java.util.stream中。因此,如果您使用的是Java 8或以上版本,則不需要額外進行安裝或下載。如果您使用的是較早的版本,可以通過以下方式進行下載:
import java.util.stream.IntStream;
下載完成後,即可通過IntStream創建對應的int流。
三、intstream.range
intstream.range方法可以用來創建一個由指定範圍的值組成的流,左閉右開區間,即包含起始值,不包含結束值。以下為示例代碼:
IntStream intStream = IntStream.range(0, 5); intStream.forEach(System.out::print); //輸出:01234
使用intstream.range方法,我們可以創建一個IntStream流,並將0到4這五個數字組成的流輸出。
四、intstream.range.foreach
IntStream.range()方法還有一個重載版本,可以帶有Consumer,用來對流中的每個元素進行操作。以下為示例代碼:
IntStream.range(0, 5).forEach(i -> System.out.print(i + " ")); //輸出:0 1 2 3 4
使用forEach方法,我們可以將流中的每個元素都列印出來。
五、intstream iterate foreach
intstream.iterate方法可以用來創建一個迭代器流,可以通過指定一個lambda表達式來定義迭代規則。以下為示例代碼:
IntStream.iterate(0, i -> i + 2).limit(5).forEach(System.out::println); //輸出:0 2 4 6 8
使用intstream.iterate方法,我們可以創建一個默認從0開始,每次迭代加2的IntStream流,並在限制範圍內輸出5個元素。
六、intstream.rangeclosed
intstream.rangeclosed方法可以用來創建一個由指定範圍的值組成的流,左閉右閉區間,即包含起始值和結束值。以下為示例代碼:
IntStream intStream = IntStream.rangeClosed(0, 5); intStream.forEach(System.out::print); //輸出:012345
使用intstream.rangeclosed方法,我們可以創建一個IntStream流,並將0到5這六個數字組成的流輸出。
七、intstream.range 源碼
我們可以看一下IntStream.range()方法的源碼:
public static IntStream range(int startInclusive, int endExclusive) { if (startInclusive >= endExclusive) { return empty(); } else if (endExclusive - startInclusive < StreamOpFlag.SIZED.getMask()) { return new IntStream.rangeInt(startInclusive, endExclusive); } else { return StreamSupport.intStream( new Streams.rangeIntSpliterator.OfInt(startInclusive, endExclusive, false), false); } }
從源碼可以看到,這個方法返回一個IntStream,它的參數是起始值和結束值。方法中首先判斷起始值是否大於等於結束值,如果是則返回一個空的IntStream。如果不是,則判斷是否需要分割,如果不需要則直接返回一個rangeInt對象,如果需要則返回一個包含分割器的intStream流。
八、intstream轉list
intstream提供的toList方法可以用來將流轉換為list,以下為示例代碼:
List list = IntStream.range(0, 5).mapToObj(i -> i).collect(Collectors.toList()); //輸出:[0, 1, 2, 3, 4]
使用toList方法,我們可以將流中的每個元素都轉化為Integer類型,並將其添加到list中,並輸出。
九、intstream collect
intstream提供了collect方法,用於將流轉換為其他類型的集合,並可以進行進一步的操作。以下為示例代碼:
List list = IntStream.range(0, 5).collect(ArrayList::new, ArrayList::add, ArrayList::addAll); //輸出:[0, 1, 2, 3, 4]
使用collect方法,我們可以將流中的元素添加到list中,並進行進一步的操作。
十、intstream.rangeclose
intstream.rangeclosed方法可以用來創建一個由指定範圍的值組成的流,左閉右閉區間,即包含起始值和結束值。以下為示例代碼:
IntStream intStream = Intstream.rangeclosed(0, 5); intStream.forEach(System.out::print); //輸出:012345
使用intstream.rangeclose方法,我們可以創建一個IntStream流,並將0到5這六個數字組成的流輸出。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/236413.html