学习任务:

视频学习

动手测试concat()

concat()方法合并两个流组成一个新流,API如下:

public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b)

从API可以开出待合并的两个流的元素类型是相同的。

测试代码如下:

//concat()测试将两个流合并为一个流
	public static void test_concat() {
		//创建collection集合
        List<PbCourse> list1 = new ArrayList<>() ;
        list1.add(new PbCourse(100L, "攀博课堂-Java面向对象教程", 33));
        list1.add(new PbCourse(101L, "攀博课堂-Spring全家桶教程", 44));
        list1.add(new PbCourse(102L, "攀博课堂-SpringCloud微服务教程", 55));
        
        List<PbCourse> list2 = new ArrayList<>() ;
        list2.add(new PbCourse(103L, "攀博课堂-在线教育分布式项目教程", 66));
        list2.add(new PbCourse(104L, "攀博课堂-电子商务项目教程", 66));
        //将两个流合并为一个流
        Stream<PbCourse> stream = Stream.concat(list1.stream(), list2.stream());
        //遍历新流
        stream.forEach(System.out::println);
	}

输出:

PbCourse [id=100, courseName=攀博课堂-Java面向对象教程, price=33]
PbCourse [id=101, courseName=攀博课堂-Spring全家桶教程, price=44]
PbCourse [id=102, courseName=攀博课堂-SpringCloud微服务教程, price=55]
PbCourse [id=103, courseName=攀博课堂-在线教育分布式项目教程, price=66]
PbCourse [id=104, courseName=攀博课堂-电子商务项目教程, price=66]

如果有多于两个集合如何使用concat合并呢?如下需求:

//将one、two、three、four依次合并,合并后的顺序为:a/b/c/d/f/g/h/i/j/k/l
String[] one = new String[]{"a","b","c"};
String[] two = new String[]{"d","e","f"};
String[] three = new String[]{"g","h","i"};
String[] four = new String[]{"j","k","l"};

测试代码如下:

	public static void test_concat_1() {
		//将one、two、three、four依次合并,合并后的顺序为:a/b/c/d/f/g/h/i/j/k/l
        String[] one = new String[]{"a","b","c"};
        String[] two = new String[]{"d","e","f"};
        String[] three = new String[]{"g","h","i"};
        String[] four = new String[]{"j","k","l"};

        Stream.concat(Stream.of(one),Stream.concat(Stream.of(two),Stream.concat(Stream.of(three),Stream.of(four))))
                .forEach(System.out::println);
	}

输出:

a
b
c
d
e
f
g
h
i
j
k
l
提问-攀博课堂
我要提问 不会就问,有效沟通
关注公众号,加入微信群交流提问。 攀博课堂官方公众号
问答列表,查看本知识点所有问题