package StreamTest; import java.util.ArrayList; import java.util.Comparator; import java.util.List; import java.util.Random; import java.util.function.IntConsumer; import java.util.stream.Collectors; import java.util.stream.IntStream; import java.util.stream.Stream; public class HomeWork { public static void main(String[] args) { IntStream is=IntStream.of(1,2,3,4); //返回流中元素的个数 //System.out.println(is.count()); //输出流中数据 //is.forEach(System.out::print); //输出1-100的总和rangeClosed()的用法 //System.out.println(IntStream.rangeClosed(1,100).sum()); System.out.println(IntStream.generate(()->5).limit(3).count()); Random rand=new Random(); //随机生成1-100之间的10个数值 IntStream is2=IntStream.generate(()->rand.nextInt(1,100)).limit(10); //is2.forEach(System.out::println); //规定输出格式 //IntConsumer ic=a->System.out.printf("%d\t",a); //is2.forEach(ic); //1 3 5 7 9 //IntStream is3=IntStream.iterate(1,a->a+2).limit(5); //IntConsumer ic=a->System.out.printf("%d\t",a); //is3.forEach(ic); //Integer转换成List<Integer> //List<Integer> list1=new ArrayList<>(List.of(1,3,5,7,8)); //IntStream is4=list1.stream().mapToInt(e->e); //List<Integer> list2=is4.boxed().collect(Collectors.toList()); //list2.forEach(System.out::println); // //IntStream is5=IntStream.empty(); //is=IntStream.of(1,2,3,4,5); //is=IntStream.range(1,4); //6 //System.out.println(is.sum()); //1 2 3 //is.forEach(System.out::println); //升序 //is2.sorted().forEach(System.out::println); //降序 //1 var is6=is2.boxed(); //is6.sorted((a,b)->b-a).forEach(System.out::println); //2 //is6.sorted(Comparator.reverseOrder()).forEach(System.out::println); //乱序 var is7= Stream.of(1,2,3); is7.sorted((a,b)->rand.nextBoolean() ?-1:1).forEach(e->System.out.printf("%d\t",e)); } }
Stream中IntStream的基本用法
最新推荐文章于 2024-07-27 10:19:50 发布