【java技术总结】Stream流基础使用

Stream流使用

1.获取Stream流

对于四种数据分别采取不同的获取方式

获取方式 方法名 说明
单列集合 default Stream stream() Collection中的默认方法
双列集合 无法直接使用Stream流
数组 public static Stream stream(T[] array) Arrays工具类中的静态方法
一堆零散数据 public static Stream of(T …values) Stream接口中的静态方法

1.1单列集合获取

List<String> list = new ArrayList<>();
Collections.addAll(list,"a","b","c");
Stream<String> stream1 = list.stream();

1.2双列集合获取

Map<String,String> map = new HashMap<>();
map.put("aaa",111);
map.put("bbb",222);
map.put("ccc",333);

Stream<String> stream1 = map.keySet().stream();
Stream<String> stream2 = map.entrySet().stream();

1.3数组获取

int[] arr1 = {1,2,3,4,5,6,7,8,9};
String[] arr2 = {"a","b","c"};

Stream<Integer> stream1 = Arrays.stream(arr1);
Stream<Integer> stream2 = Arrays.stream(arr2);

1.4零散数据

Stream<Integer> stream1 = Stream.of(1,2,3,4);
Stream<String> stream2 = Stream.of("a","b","c","d");

2.Stream流的中间方法

名称 说明
Streamfilter(Predicate<? super T> predicate) 过滤
Streamlimit(long maxSize) 获取前几个元素
Stream skip(long n) 跳过前几个元素
Stream distinct() 元素去重,依赖(hashCode和equals方法)
static Stream concat(Stream a,Stream b) 合并a和b两个流为一个流
Stream map(Function<T,R> mapper) 转换流中的数据类型
List<String> list = new ArrayList<String>();
Collections.addAll(list,"张三丰","周芷若","赵明");

2.1filter

list.stream().filter(s -> s.startsWith("张"));

2.2limit

list.stream().limit(3);

2.3skip

list.stream().skip(4);

2.4distinct

list.stream().distinct();

2.5concat

Stream.concat(list1.stream(),list2.stream());

2.6map

List<String> list = new ArrayList<>();
Collections.addAll(list,"张无忌-15","周芷若-56","赵敏-52","张三丰-100");

list.stream().map(s -> Integer.parseInt(s.split("-")[1]));

3.Stream流的终结方法

名称 说明
void forEach(Consumer action) 遍历
long count() 统计
toArray() 收集流中的数据,放到数组中
collect(Collector collector) 收集流中的数据,放到集合中
List<String> list = new ArrayList<String>();
Collections.addAll(list,"张三丰","周芷若","赵明");

3.1forEach遍历

list.stream().forEach(s -> System.out.println(s));

3.2count统计

long count = list.stream().count();

3.3toArray()收集流中数据,放到数组中

String[] arr = list.stream().toArray(value -> new String[value]);

3.4collect(Collector collector)

  1. 收集流中数据,放到List集合中
List<String> newList = list.stream().collect(Collectors.toList());
  1. 收集流中数据,放到Set集合中
Set<String> set = list.stream()
    .filter(s -> "男".equals(s.split("-")[1]))
    .collect(Collectors.toSet());

3.收集流中数据,放到Set集合中

Map<String, String> collect = list.stream().filter(s -> "男".equals(s.split("-")[1]))
    .collect(Collectors.toMap(s -> s.split("-")[0], s -> s.split("-")[2]));
posted @ 2023-01-19 21:30  求道之愚者  阅读(70)  评论(0)    收藏  举报