jdk8中关于操作集合的一些新特性,遍历和排序操作

时间:2022-12-07 14:50:16

jdk8增加了不少新的东西,在集合操作这块,就有如 lamda表达式,stream,sort,optional等新的类,主要涉及遍历和排序等方面,新特性提升了不少性能,我们开发就是要拥抱新事物,守着老食物总会落后,跟不上节奏,下面是自己的新特性的一些demo

public class Java8Test {
private static Logger logger = LoggerFactory.getLogger(Java8Test.class);
public static void java8test(){
List<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
list.add(6);
/* list.forEach(e ->{
System.out.println(e);
});*/
List<Integer> views = new ArrayList<>();
Optional<List<Integer>> data = Optional.ofNullable(list);
data.get().stream().filter(x -> {
return x>=3;
}).forEach(System.out::println);
}

public static void sort(){
Model model1 = new Model("zhangsan4",18);
Model model2 = new Model("zhangsan5",18);
Model model3 = new Model("zhangsan3",17);
Model model4 = new Model("zhangsan1",19);
Model model5 = new Model("zhangsan2",18);
Model model6 = new Model("zhangsan6",21);
List<Model> sortlist = new ArrayList<>();
sortlist.add(model1);
sortlist.add(model2);
sortlist.add(model3);
sortlist.add(model4);
sortlist.add(model5);
sortlist.add(model6);
sortlist = sortlist.stream().sorted((s1,s2)->{
String a1 = null;
String a2 = null;
Optional<String> num1 = Optional.ofNullable(s1.getName());
Optional<String> num2 = Optional.ofNullable(s2.getName());
if(num1.isPresent() && num2.isPresent()){
a1 = num1.get();
a2 = num2.get();
}
if(a1!=null&&a2!=null){
return a1.compareTo(a2);
}else{
return 0;
}
}).sorted((x1,x2) -> {
Integer a1 = null;
Integer a2 = null;
try {
Optional<Integer> num1 = Optional.ofNullable(x1.getAge());
Optional<Integer> num2 = Optional.ofNullable(x2.getAge());
if(num1.isPresent() && num2.isPresent()){
a1 = num1.get();
a2 = num2.get();
}
} catch (NumberFormatException e) {
e.printStackTrace();
logger.error("转整型异常",e);
}
if (a1!=null&&a2!=null){
return a1.compareTo(a2);
}else{
return 0;
}

}).collect(Collectors.toList());
sortlist.forEach(e ->{
System.out.println(e);
});
}

public static void main(String[] args) {
// java8test();
sort();

}

}
class Model{
private String name;
private int age;

public Model(String name, int age) {
super();
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "Model [name=" + name + ", age=" + age + "]";
}

}