关键字: List.sort(), collect(), filter()
问题发现
[Java 1.8]
在测试代码时发现使用 ArrayList.stream().filter(...).collect(Collectors.toList()).sort()
对List进行过滤排序时,并没有起到想要的效果
寻找原因
1. collect
collect 会返回处理后的List,并不会在原有基础上做修改,在上文中使用时并没有接收处理后的List,所以看起来没做任何处理。
先修正为aNewList = ArrayList.stream().filter(...).collect(Collectors.toList()).sort()
,看结果还是失败了!那应该还有其他原因。
2. 先拆分试试看
aNewList = ArrayList.stream().filter(...).collect(Collectors.toList())
aNewList.sort()
过滤排序成功,查看List.sort函数,发现sort并没有返回值!找到原因了:
写成filter().collect().sort()
时,是在collect()的返回list上进行排序,但是sort并不会有返回值。相当于在一个临时的List上做了过滤排序,但结束后该List就被销毁了,你也无法获取其结果,相当做了无用功。
3. 推荐写法
// 拆分写
aNewList = ArrayList.stream().filter(...).collect(Collectors.toList())
aNewList.sort()
// 用sorted函数
aNewList = ArrayList.stream().filter(...).sorted().collect(Collectors.toList())
测试代码
// point 类
public class point {
private String pointCode;
private String pointSize;
point(String pointcode, String pointsize) {
this.pointCode = pointcode;
this.pointSize = pointsize;
}
public String getPointCode() {
return pointCode;
}
public void setPointCode(String pointCode) {
this.pointCode = pointCode;
}
public String getPointSize() {
return pointSize;
}
public void setPointSize(String pointSize) {
this.pointSize = pointSize;
}
}
// 过滤操作
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
import Study1009.point;
public class testfilter {
public static void main(String []args) {
List<String> filtereList = Arrays.asList("S", "R", "G", "T");
point defect1 = new point("a", "G");
point defect2 = new point("b", "R");
point defect3 = new point("c", "T");
point defect4 = new point("d", "S");
point defect5 = new point("e", "I");
List<point> defectList = new ArrayList<point>();
defectList.add(defect1);
defectList.add(defect2);
defectList.add(defect3);
defectList.add(defect4);
defectList.add(defect5);
// 过滤失败
defectList.stream().filter(O -> filtereList.contains(O.getPointSize())).collect(Collectors.toList());
// 过滤成功
defectList = defectList.stream().filter(O -> filtereList.contains(O.getPointSize()))
.collect(Collectors.toList());
// 过滤排序失败 error: Type mismatch: cannot convert from void to List<Defect>
// defectList = defectList.stream().filter(O -> filtereList.contains(O.getPointSize()))
// .collect(Collectors.toList()).sort(Comparator.comparingInt(O -> judgeList.indexOf(O.getPointSize())));
// 过滤成功
defectList = defectList.stream().filter(O -> filtereList.contains(O.getPointSize()))
.collect(Collectors.toList());
defectList.sort(Comparator.comparingInt(O -> filtereList.indexOf(O.getPointSize())));
// 过滤成功, 但要接收collect的返回结果,否则原List没有发生改变
defectList = defectList.stream().filter(O -> filtereList.contains(O.getPointSize()))
.sorted(Comparator.comparingInt(O -> filtereList.indexOf(O.getPointSize()))).collect(Collectors.toList());
for (int i=0; i<defectList.size(); i++) {
System.out.println(defectList.get(i).getPointCode() + "-" + defectList.get(i).getPointSize() + " ");
}
}
}