场景:在统计时,使用group by
分组函数时。若想获取除分组参数外的其他数据,推荐在select上使用GROUP_CONCAT(id)
函数。这样得到的数据就使用,
分割。
需求:将集合中对象的使用,
分割的字段转换成一个新的集合。
方案1:使用flatMap
public class TestArray {
/**
* 方案1,使用flatMap(相当双层for循环)进行数据的汇总
*/
public static void main(String[] args) {
List<Student> students = data1();
//第一层for循环遍历对象。
List<String> sports = students.stream().
filter(s -> s.getSports() != null).
//第二层for循环获取到所有的元素流。
flatMap(s -> Arrays.stream(s.getSports().split(","))).
//二层循环结束后开始汇总数据
collect(Collectors.toList());
System.out.println(sports);
}
public static List<Student> data1() {
return new ArrayList<>();
}
public static List<Student> data2() {
List<Student> stus = new ArrayList<>();
Student s1 = new Student();
s1.setName("李白");
s1.setSports("足球,篮球");
Student s2 = new Student();
stus.add(s1);
stus.add(s2);
return stus;
}
@Data
public static class Student {
private String name;
/**
* 运动类型。使用,进行分割。
* eg: 足球,篮球
*/
private String sports;
}
}
2. 方案2:使用Collectors.joining()
public class TestArray {
public static void main(String[] args) {
List<Student> students = data2();
//将列表中所有的该字段在使用,进行连接
String strs = students.stream().
map(Student::getSports).
filter(StringUtils::isNotBlank).
collect(Collectors.joining());
//然后在进行统一切分
List<String> collect = Arrays.stream(strs.split(",")).collect(Collectors.toList());
System.out.println(collect);
}
public static List<Student> data1() {
return new ArrayList<>();
}
public static List<Student> data2() {
List<Student> stus = new ArrayList<>();
Student s1 = new Student();
s1.setName("李白");
s1.setSports("足球,篮球");
Student s2 = new Student();
s2.setSports("");
stus.add(s1);
stus.add(s2);
return stus;
}
@Data
public static class Student {
private String name;
/**
* 运动类型。使用,进行分割。
* eg: 足球,篮球
*/
private String sports;
}
}
3. 注意点:对空串或者null进行切割
对空串进行分割,得到的集合大小为1。
public static void main(String[] args) {
String str="";
List<String> collect = Arrays.stream(str.split(";")).collect(Collectors.toList());
System.out.println("空串的大小:"+collect.size());
String str1=null;
List<String> collect1 = Arrays.stream(str1.split(";")).collect(Collectors.toList());
System.out.println("null的大小:"+collect1.size());
}
空串的大小:1
Exception in thread "main" java.lang.NullPointerException
所以使用Arrays.stream(str.split(";")).collect(Collectors.toList())
时,需要对字符串进行校验~
网友评论