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);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章