当前位置:   article > 正文

java中的Stream流

java中的Stream流

Logback日志级别(从大到小)

1:error:错误

2:warn:警告

3:info:信息
4:debug:调试

5:trace:追踪(例如:追踪用户行为轨迹)

Stream流

针对集合进行功能简化

Stream流通常结合Lambda表达式来使用

Stream流方法分类:

1:获取方法:获取流(创建一个流水线)

2:中间方法:在流水线进行操作(例如:过滤,截取)

3:终结方法:流水线上的操作结束了,要关闭流水线 

Stream流获取方法

单列集合:Collection[list,set]

可以使用Collection接口中的默认方法Stream()生成流

default Stream<E> stream()

Returns a sequential Stream with this collection as its source. 

Stream 流对象=单列集合对象.Stream();

 双列集合:Map(不能直接获取流对象)

间接获取流对象

先通过keyset()或entryset(),获取set集合

Stream 流对象=set集合对象.stream();

数组 :

Stream 流对象=Arrays.stream(数组);

多个同一类型元素:
使用Stream流中的静态方法,可以把同一种类型元素封装成Stream流对象

static <T> Stream<T> of(T... values)

运用可变参数

Stream 流对象=Stream.of(1,2,3); 

  1. public class test {
  2. public static void main(String[] args) {
  3. //单列集合获取流对象
  4. List<String>list=new ArrayList<>();
  5. Collections.addAll(list,"java1","java2","java3","c++1","c++2");
  6. Stream<String> stream = list.stream();
  7. //map集合获取流对象
  8. HashMap<Integer,String>map=new HashMap<Integer, String>();
  9. map.put(1,"java1");
  10. map.put(2,"java2");
  11. // Set<Integer>set=map.keySet();
  12. //Stream<Integer>stream1=set.stream();
  13. Set<Map.Entry<Integer, String>> entries = map.entrySet();
  14. Stream<Map.Entry<Integer,String>>stream1=entries.stream();
  15. //数组获取流对象
  16. Integer []arr={1,2,3};//得用包装类型
  17. Stream<Integer> stream2 = Arrays.stream(arr);
  18. //Stream<Integer>stream2=Arrays.stream(arr);
  19. //同一类型获取流对象
  20. Stream<Integer> integerStream = Stream.of(1, 2, 3);
  21. }
  22. }

Stream流中间方法:

过滤方法:

Stream<T> filter(Predicate<? super T> predicate)

Returns a stream consisting of the elements of this stream that match the given predicate.

  1. public class test2 {
  2. public static void main(String[] args) {
  3. //单列集合获取流对象
  4. List<String> list=new ArrayList<>();
  5. Collections.addAll(list,"java1","java2","java3","c++1","c++2");
  6. /* Stream<String> stream = list.stream();
  7. //获取所有java开头的元素,并打印
  8. *//*stream.filter(new Predicate<String>() {
  9. @Override
  10. public boolean test(String s) {
  11. return s.startsWith("java");
  12. }
  13. });*//*
  14. Stream<String>stream1=stream.filter(s->s.startsWith("java"));//获取所有以java开头的元素
  15. *//* stream1.forEach(new Consumer<String>() {
  16. @Override
  17. public void accept(String s) {
  18. }
  19. });*//*
  20. //stream1.forEach(s-> System.out.println(s));//实例方法引用
  21. stream1.forEach(System.out::println);//打印*/
  22. //我们可以直接链式
  23. list.stream()
  24. .filter(s->s.startsWith("java"))
  25. .forEach(System.out::println);
  26. }
  27. }

 截取方法:
Stream<T> limit(long maxSize)

截取指定参数个数的数据

  1. public class test3 {
  2. public static void main(String[] args) {
  3. List<String> list=new ArrayList<>();
  4. Collections.addAll(list,"java1","java2","java3","c++1","c++2");
  5. list.stream()
  6. .limit(4)//中间方法,只截取前四个元素
  7. .forEach(System.out::println);
  8. /*java1
  9. java2
  10. java3
  11. c++1*/
  12. }
  13. }

跳过方法:

 Stream<T> skip(long n)

跳过指定参数个数的数据

  1. list.stream()
  2. .skip(3)//中间方法,跳过n个元素
  3. .forEach(System.out::println);
  4. /* c++1
  5. c++2*/

 合取方法:
static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

合并a,b两个流变成一个流

  1. public class test4 {
  2. public static void main(String[] args) {
  3. List<String >list1=new ArrayList<>();
  4. Collections.addAll(list1,"java1","java2","java3");
  5. List<String>list2=new ArrayList<>();
  6. Collections.addAll(list2,"c++1","c++2");
  7. //获取两个流对象
  8. Stream<String> stream1=list1.stream();
  9. Stream<String>stream2=list2.stream();
  10. //合并
  11. Stream<String> concat = Stream.concat(stream1, stream2);
  12. concat.forEach(System.out::println);
  13. /*java1
  14. java2
  15. java3
  16. c++1
  17. c++2*/
  18. }
  19. }

 去除方法:
Stream<T> distinct()

去除流中重复的元素,依赖(hashCode和equals方法)

假如流中存储的是自定义对象,要在对象中重写hashCode和equals方法

  1. public class test5 {
  2. public static void main(String[] args) {
  3. List<String> list=new ArrayList<>();
  4. Collections.addAll(list,"java1","java1","java3","c++1","c++2");
  5. list.stream()
  6. .distinct()
  7. .forEach(System.out::println);
  8. /*java1
  9. java3
  10. c++1
  11. c++2*/
  12. }
  13. }

 类型转换方法:

<R> Stream<R> map(Function<? super T,? extends R> mapper)

将流中元素类型进行转换

  1. class People
  2. {
  3. private String name;
  4. public People(String name) {
  5. this.name = name;
  6. }
  7. public String getName() {
  8. return name;
  9. }
  10. public void setName(String name) {
  11. this.name = name;
  12. }
  13. @Override
  14. public String toString() {
  15. return "People{" +
  16. "name='" + name + '\'' +
  17. '}';
  18. }
  19. }
  20. class Superman
  21. {
  22. private String name;
  23. public Superman(String name) {
  24. this.name = name;
  25. }
  26. public String getName() {
  27. return name;
  28. }
  29. public void setName(String name) {
  30. this.name = name;
  31. }
  32. @Override
  33. public String toString() {
  34. return "Superman{" +
  35. "name='" + name + '\'' +
  36. '}';
  37. }
  38. }
  39. public class test6 {
  40. public static void main(String[] args) {
  41. List<People>list=new ArrayList<>();
  42. list.add(new People("hhh"));//这里存的是People类型
  43. list.stream().map(new Function<People,Superman>() {
  44. @Override
  45. public Superman apply(People people) {
  46. return new Superman(people.getName());
  47. }
  48. })
  49. .forEach(System.out::println);//打印出来Superman类型,说明类型发生转换Superman{name='hhh'}
  50. list.stream()
  51. .map(people -> new Superman(people.getName()))
  52. .forEach(System.out::println);
  53. }
  54. }

 排序方法:

Stream<T> sorted()

Stream<T> sorted(Comparator<? super T> comparator)

  1. public class test7 {
  2. public static void main(String[] args) {
  3. List<Integer>list=new ArrayList<>();
  4. Collections.addAll(list,1,5,9,3,6);
  5. //使用sort排序
  6. list.stream()
  7. .sorted()//默认升序
  8. .forEach(System.out::println);
  9. /*list.stream()
  10. .sorted(new Comparator<Integer>() {
  11. @Override
  12. public int compare(Integer o1, Integer o2) {
  13. return o2-o1;
  14. }
  15. });*/
  16. list.stream()
  17. .sorted((o1,o2)->o2-o1)//降序
  18. .forEach(System.out::println);
  19. }
  20. }

练习:
 

  1. class Book
  2. {
  3. private String name;
  4. public Book() {
  5. }
  6. public Book(String name) {
  7. this.name = name;
  8. }
  9. public String getName() {
  10. return name;
  11. }
  12. public void setName(String name) {
  13. this.name = name;
  14. }
  15. @Override
  16. public String toString() {
  17. return "Book{" +
  18. "name='" + name + '\'' +
  19. '}';
  20. }
  21. }
  22. public class practice {
  23. public static void main(String[] args) {
  24. ArrayList<String>list1=new ArrayList<>();
  25. Collections.addAll(list1,"java1","java2","java3","java4","c++1","c++2");
  26. ArrayList<String>list2=new ArrayList<>();
  27. Collections.addAll(list2,"mysql1","mysql2","mysql3","oracle1","oracle2");
  28. //第一个队列只要名字是5个字符,且只要前三个
  29. Stream<String> stream1 = list1.stream()
  30. .filter(s -> s.length() == 5)
  31. .limit(3);
  32. //第二个队伍只要mysql,且跳过前两个
  33. Stream<String> stream2 = list2.stream()
  34. .filter(s -> s.startsWith("mysql"))
  35. .skip(2);
  36. //把两个队伍合并起来
  37. Stream<String>stream=Stream.concat(stream1,stream2);
  38. //把stream中的内容变成Book类
  39. Stream<Book> bookStream = stream.map(s -> new Book(s));
  40. //验证:
  41. bookStream.forEach(System.out::println);
  42. /* Book{name='java1'}
  43. Book{name='java2'}
  44. Book{name='java3'}
  45. Book{name='mysql3'}*/
  46. }
  47. }

Stream流的终结方法:


void forEach(Consumer<? super T> action)

Performs an action for each element of this stream.

对此流的每个元素进行操作

Optional<T> min(Comparator<? super T> comparator)

Returns the minimum element of this stream according to the provided Comparator. This is a special case of a reduction.

返回此流中最小元素 

Optional<T> max(Comparator<? super T> comparator)

Returns the maximum element of this stream according to the provided Comparator. This is a special case of a reduction.

 返回此流中最大元素 

long count()

Returns the count of elements in this stream. 

返回此流中的元素数 

  1. public class test8 {
  2. public static void main(String[] args) {
  3. ArrayList<Integer>list=new ArrayList<>();
  4. Collections.addAll(list,2,8,5,3,9);
  5. //求最小值
  6. System.out.println(list.stream()
  7. .min((o1, o2) -> o1 - o2));//返回的是排序后坐标最小的
  8. System.out.println(list.stream()
  9. .max((o1, o2) -> o1 - o2));//返回的是排序后坐标最大的
  10. //求流中偶数的个数
  11. long count=list.stream()
  12. .filter(i->i%2==0)
  13. .count();
  14. //count()是终结方法,想再次使用必须重新创建
  15. }
  16. }

 Stream流中的收集方法:


<R,A> R collect(Collector<? super T,A,R> collector)

把流中的数据收集到集合中

 <A> A[] toArray(IntFunction<A[]> generator)

把流中的数据收集到数组中

  1. public class test9 {
  2. public static void main(String[] args) {
  3. ArrayList<Integer>list=new ArrayList<>();
  4. Collections.addAll(list,1,2,3,4,5,6,7,8,9);
  5. List<Integer> collect = list.stream()
  6. .filter(i -> i % 2 == 0)
  7. .collect(Collectors.toList());//收集流中数据到List集合
  8. System.out.println(collect);
  9. Integer[]arr= list.stream()
  10. .filter(i->i%2==0)
  11. .toArray(value-> new Integer[value]);//value是数组的大小
  12. System.out.println(Arrays.toString(arr));
  13. }
  14. }

 

  1. public class test10 {
  2. public static void main(String[] args) {
  3. ArrayList<String>list=new ArrayList<>();
  4. Collections.addAll(list,"hhh,18","xxx,20","ccc,38");
  5. //获取年龄大于20岁的,并将其存到Map集合
  6. /* list.stream()
  7. .filter(s->{
  8. String[] split = s.split(",");
  9. Integer age=Integer.parseInt(split[1]);
  10. return age>=20;
  11. });*/
  12. /* list.stream()
  13. .filter(s->Integer.parseInt(s.split(",")[1])>=20)
  14. .collect(Collectors.toMap(new Function<String, Object>() {
  15. @Override
  16. public Object apply(String s) {
  17. return null;
  18. }
  19. }))*/
  20. Map<String, String> map = list.stream()
  21. .filter(s -> Integer.parseInt(s.split(",")[1]) >= 20)
  22. .collect(Collectors.toMap(s -> s.split(",")[0], s -> s.split(",")[1]));
  23. System.out.println(map);//{ccc=38, xxx=20}
  24. }
  25. }

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/445754
推荐阅读
相关标签
  

闽ICP备14008679号