1、集合元素处理(传统方式)
- 现在有两个ArrayList集合存储队伍当中的多个成员姓名,要求使用传统的for循环(或增强for循环)依次进行一下若干操作步骤:
- 第一个队伍只要 名字为 3 个字 的成员姓名;存储到一个新集合中。
- 第一个队伍筛选之后只要 前 3 个人;存储到一个新集合中。
- 第二个队伍只要姓 张 的成员姓名;存储到一个新集合中。
- 第二个队伍筛选之后 不要前 2 个人;存储到一个新集合中。
- 将两个队伍 合并 为一个队伍;存储到一个新集合中。
- 根据姓名创建Person对象;存储到一个新集合中。
- 打印整个队伍的Person对象信息。
package com.csdn.streampractice;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.Collections;
public class Traditional {
public static void main(String[] args) {
ArrayList one = new ArrayList<>();
Collections.addAll(one, "喜羊羊", "美羊羊", "懒洋洋", "灰太狼", "红太狼", "村长");
ArrayList one1 = new ArrayList<>();
for (String name : one) {
ArrayList one2 = new ArrayList<>();
for (int i = 0; i < 3; i++) {
ArrayList two = new ArrayList<>();
Collections.addAll(two, "张三丰", "张翠山", "张无忌", "赵敏", "周芷若");
ArrayList two1 = new ArrayList<>();
for (String name : two) {
if (name.startsWith("张")) {
ArrayList two2 = new ArrayList<>();
for (int i = 2; i
ArrayList concatenate = new ArrayList<>();
concatenate.addAll(one2);
concatenate.addAll(two2);
ArrayList
list = new ArrayList<>(); for (String name : concatenate) {
list.add(new Person(name));
for (Person person : list) {
System.out.println(person);
2、集合元素处理(Stream方式)
package com.csdn.streampractice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Stream;
public class DemoStreamNames {
public static void main(String[] args) {
ArrayList one = new ArrayList<>();
Collections.addAll(one, "喜羊羊", "美羊羊", "懒洋洋", "灰太狼", "红太狼", "村长");
Stream stream = one.stream();
Stream stringStream = stream.filter(name -> name.length() == 3);
Stream limit = stringStream.limit(3);
ArrayList two = new ArrayList<>();
Collections.addAll(two, "张三丰", "张翠山", "张无忌", "赵敏", "周芷若");
Stream stream1 = two.stream();
Stream stringStream1 = stream1.filter(name -> name.startsWith("张"));
Stream skip = stringStream1.skip(2);
Stream concat = Stream.concat(limit, skip);
Stream
personStream = concat.map(name -> new Person(name)); personStream.forEach(System.out::println);
- 完全使用链式编程,lambda表达式和方法引用完成代码
package com.csdn.streampractice;
import java.util.ArrayList;
import java.util.Collections;
import java.util.stream.Stream;
public class StreamUltimate {
public static void main(String[] args) {
ArrayList one = new ArrayList<>();
Collections.addAll(one, "喜羊羊", "美羊羊", "懒洋洋", "灰太狼", "红太狼", "村长");
Stream limit = one.stream().filter(name -> name.length() == 3).limit(3);
ArrayList two = new ArrayList<>();
Collections.addAll(two, "张三丰", "张翠山", "张无忌", "赵敏", "周芷若");
Stream skip = two.stream().filter(name -> name.startsWith("张")).skip(2);
Stream.concat(limit, skip).map(Person::new).forEach(System.out::println);