当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Java Spliterator trySplit()用法及代码示例


Java Interface Spliterator 的 trySplit() 方法用于拆分调用的拆分器。如果此拆分器可以分区,则返回对该分区的新拆分器的引用,否则返回 null。

用法

以下是 trySplit() 方法的声明-

Spliterator<T> trySplit()

参数

此方法不接受任何参数。

返回

trySplit() 方法返回一个覆盖部分元素的拆分器,如果此拆分器无法拆分,则返回 null。

异常

NA

兼容版本

Java 1.8 及以上

例子1

import java.util.*;
public class InterfaceSpliteratorTrySplitExample1 {  
	public static void main (String[] args) {
		List<String> list = Arrays.asList("Java", "Android", "MySQL", "Python");
		Spliterator<String> splitr = list.spliterator();
		Spliterator<String> st = splitr.trySplit();
		splitr.forEachRemaining(System.out::println);
		System.out.println("--Traversing the other half of the spliterator---");
		st.forEachRemaining(System.out::println);
    }
}

输出:

MySQL
Python
--Traversing the other half of the spliterator---
Java
Android

例子2

import java.util.*;
import java.util.stream.Stream;
public class InterfaceSpliteratorTrySplitExample2 {  
     public static void main(String args[]){
    	   //Create an object of array list
         ArrayList<Integer> list = new ArrayList<>();             
         //Add values to the array list.
         list.add(101);
         list.add(201);
         list.add(301);
         list.add(401);
         list.add(501);                      
         Stream<Integer> str = list.stream();             
         //Get Spliterator object on list
         Spliterator<Integer> splitr1 = str.spliterator();                             
         System.out.println("Elements of ArrayList:");
         //forEachRemaining method    
         splitr1.forEachRemaining((n) -> System.out.println(n));         
         //Obtaining another Stream to the array list.
         Stream<Integer> str1 = list.stream();
         splitr1 = str1.spliterator();          
         //Use trySplit() method
         Spliterator<Integer> splitr2 = splitr1.trySplit();        
         System.out.println("Output from splitr2:");
         splitr2.forEachRemaining((n) -> System.out.println(n));        
         //Now, use the splitr
         System.out.println("Output from splitr1:");
         splitr1.forEachRemaining((n) -> System.out.println(n));
         }
}

输出:

Elements of ArrayList:
101
201
301
401
501
Output from splitr2:
101
201
Output from splitr1:
301
401
501



相关用法


注:本文由纯净天空筛选整理自 Java Spliterator trySplit() Method。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。