本文共 7049 字,大约阅读时间需要 23 分钟。
/** * @author zhangdi * @description 常用的流操作 */public class LambdaChapter3_3 { public static void main(String[] args) { // new LambdaChapter3_3().testCollect(); // new LambdaChapter3_3().testMap_usingMap(); // new LambdaChapter3_3().testfilter_usingLambda(); // new LambdaChapter3_3().testflatMap(); new LambdaChapter3_3().testMaxAndMin(); }// 3.3.1 collect(toList()) :collect(toList()) 方法由 Stream 里的值生成一个列表, // 是一个及早求值操作。 public void testCollect() { List collected = Stream.of("a", "b", "c") // <1> .collect(Collectors.toList()); // <2> assertEquals(Arrays.asList("a", "b", "c"), collected); // <3> } // 3.3.2 map 如果有一个函数可以将一种类型的值转换成另外一种类型, map 操作就可以使用该函数, 将一个流中的值转换成一个新的流 /** * 使用 for 循环将字符串转换为大写 */ public void testMap_usingFor() { List collected = new ArrayList<>(); for (String string : asList("a", "b", "hello")) { String upperCase = string.toUpperCase(); collected.add(upperCase); } assertEquals(asList("A", "B", "HELLO"), collected); } /** * 使用 map 循环将字符串转换为大写 */ public void testMap_usingMap() { List collected = Stream.of("a", "b", "hello").map(string -> string.toUpperCase()) .collect(Collectors.toList()); } // 3.3.3 filter ;遍历数据并检查其中的元素时, 可尝试使用 Stream 中提供的新方法 filter /** * 使用循环遍历列表, 使用条件语句做判断 */ public void testfilter_usingFor() { List beginningWithNumbers = new ArrayList<>(); for (String value : asList("Demacia", "Bilgewater", "2Valoran")) { if (isDigit(value.charAt(0))) { beginningWithNumbers.add(value); } } assertEquals(asList("2Valoran"), beginningWithNumbers); } /** * 函数式风格 */ public void testfilter_usingLambda() { List beginningWithNumbers = Stream.of("Demacia", "Bilgewater", "2Valoran") .filter((value) -> isDigit(value.charAt(0))).collect(toList()); assertEquals(asList("2Valoran"), beginningWithNumbers); } // 3.3.4 flatMap: flatMap 方法可用 Stream 替换值, 然后将多个 Stream 连接成一个 Stream // 前面已介绍过 map 操作, 它可用一个新的值代替 Stream 中的值。 但有时, 用户希望让 map // 操作有点变化, 生成一个新的 Stream 对象取而代之。 /** * Question:假设有一个包含多个列表的流, 现在希望得到所有数字的序列。 * 包含多个列表的 Stream */ public void testflatMap() { List together = Stream.of(asList(1, 2), asList(3, 6)).flatMap(value -> value.stream()) .collect(toList()); assertEquals(asList(1, 2, 3, 6), together); } // 3.3.5 max和min:Stream 上常用的操作之一是求最大值和最小值 /** * 使用 Stream 查找最短曲目 */ public void testMaxAndMin() { List
转载地址:http://wawji.baihongyu.com/