💎一站式轻松地调用各大LLM模型接口,支持GPT4、智谱、星火、月之暗面及文生图 广告
### 3.3.1 flatMap的用法 通过`map`操作,可以**改变流中元素的类型**,以下代码将String流映射成了Integer流: ```java List<String> strList = Arrays.asList("stream", "map", "flatMap"); /* 将字符串列表转成长度列表 */ List<Integer> hashCodeList = strList.stream() .map(String::length) .collect(Collectors.toList()); System.out.println(hashCodeList); ``` 这里可以将其优化为输出int流,以避免装箱的性能损耗: ```java /* 性能优化点,避免装箱 */ int[] hashCodeArr = strList.stream() .mapToInt(String::length) .toArray(); System.out.println(Arrays.toString(hashCodeArr)); ``` ---- `flatMap`的效果是**映射成流的内容**,下面的代码中,需要选出所有的字符并去重。 `map`操作返回的是`String[]`流,可以通过`flatMap`操作转成String流,得到最终结果: ```java /* 选出所有的字符,并去重 */ List<String[]> contextStrList = strList.stream() .map(str -> str.split("")) .distinct() .collect(Collectors.toList()); System.out.println(Arrays.deepToString(contextStrList.toArray())); /* 只使用map达不到效果 [[s, t, r, e, a, m], [m, a, p], [f, l, a, t, M, a, p]] */ List<String> contextList = strList.stream() .map(str -> str.split("")) .flatMap(strArr -> Arrays.stream(strArr)) .distinct() .collect(Collectors.toList()); System.out.println(Arrays.deepToString(contextList.toArray())); /* flatMap的效果是映射成流的内容 [s, t, r, e, a, m, p, f, l, M] */ ```