Stream编程 - 案例总结

随机数

List<Integer> collect = ThreadLocalRandom.current()
  .ints(0,9)
  .limit(10)
  .boxed()
  .collect(Collectors.toList());
System.out.println(collect);

获取数组最小的值

int[] nums = new int[]{7,3,4,5};
int value = IntStream.of(nums)
  .min()
  .getAsInt();
System.out.println(value);

并行方式

int[] nums = new int[]{7,3,4,5};
int value = IntStream.of(nums)
  .parallel()
  .min()
  .getAsInt();
System.out.println(value);

数组转换

int[] nums = new int[]{7,3,4,5};
List<String> strings = Arrays.stream(nums)
  .boxed()
  .map(Object::toString)
  .collect(Collectors.toList());
System.out.println(strings);

并发处理,同步返回

List<String> strings = Arrays.asList("www.baidu.com", "1s.app");
List<String> collect = strings.parallelStream()
  .map(source -> {
    // 耗时操作
    return "http://" + source;
  }).filter(Objects::nonNull)
  .collect(Collectors.toList());
System.out.println(collect);

数组只取一项目

String value = Stream.of("www.baidu.com", "1.app")
  .map(s -> {
    if (s.endsWith("app")){
      return s;
    }
    return null;
  })
  .filter(Objects::nonNull)
  .findFirst()
  .orElseThrow(() -> new Exception("未找到"));

System.out.println(value);

去重

@Data 提供类所有属性的 get 和 set 方法,此外还提供了equals、canEqual、hashCode、toString 方法。

不懂 Lombok可以查看 [Lombok 的使用](Lombok 的使用.md)

@Data
@AllArgsConstructor
public static class Person{
  private String name;
  private int age;
}
List<Person> collect = Stream.of(
  new Person("张三", 13),
  new Person("小红", 15),
  new Person("张三", 13))
  .distinct()
  .collect(Collectors.toList());
System.out.println(collect);

分组

@Data
@AllArgsConstructor
public static class Student{
  // 班级
  private String cls;
  // 姓名
  private String name;
}
List<Student> students = Arrays.asList(
        new Student("一年级", "张三"),
        new Student("一年级", "李四"),
        new Student("二年级", "小红")
);
Map<String, List<Student>> collect = students.stream()
  .collect(Collectors.groupingBy(Student::getCls));

//查看
Set<String> clsSets = collect.keySet();
for(String key : clsSets){
  System.out.println("班级:" + key);
  List<Student> list = collect.get(key);
  System.out.println("学生:" + list);
}

数组合并,并去重

List<String> names1 = Arrays.asList("小明", "小红", "小花");
List<String> names2 = Arrays.asList("小明","小刘", "小珂", "小张");
List<String> collect = Stream.concat(names1.stream(), names2.stream())
  .distinct()
  .collect(Collectors.toList());
// [小明, 小红, 小花, 小刘, 小珂, 小张]
System.out.println(collect);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章