目录
1.数据准备
2.对象数组的排序
1.实现Comparable类
2.实现Comparator类
3.匿名Comparator
3.数组常用Stream(jdk1.8)
1.数据准备
People类
public class People {
private String name;
private String sex;
private Integer age;
public People(String name, String sex, Integer age) {
this.name = name;
this.sex = sex;
this.age = age;
}
public People() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
@Override
public String toString() {
return "People{" +
"name='" + name + ''' +
", sex='" + sex + ''' +
", age=" + age +
'}';
}
}
List list = new ArrayList<>();
list.add(new People("张三","男",21));
list.add(new People("李四","女",23));
list.add(new People("王五","男",26));
list.add(new People("赵六","女",21));
2.对象数组的排序
1.实现Comparable类
主要是使用Comparable类,实现其中的compareTo方法进行数据比较
在People类中实现Comparable
public class People implements Comparable
此时会要求实现compareTo方法
@Override
public int compareTo(People o) {
if(o.getAge()>this.getAge()){
return 1;
}else if(o.getAge() == this.getAge()){
return 0;
}else {
return -1;
}
}
Listlist = new ArrayList<>(); list.add(new People("张三","男",21)); list.add(new People("李四","女",23)); list.add(new People("王五","男",26)); list.add(new People("赵六","女",21)); Collections.sort(list);
上边是按年龄降序进行排序,返回值一共有三种情况,大于0,小于0,等于0这三种。
若想要按年龄降序,可以把返回值1和-1的位置进行调换,或把判断条件的大于号改成小于号。
2.实现Comparator类
在People类中实现Comparator
public class People implements Comparator
此时会要求实现compare方法
@Override
public int compare(People o1, People o2) {
if(o1.getAge()>o2.getAge()){
return 1;
}else if(o1.getAge() == o2.getAge()){
return 0;
}else {
return -1;
}
}
Listlist = new ArrayList<>(); list.add(new People("张三","男",21)); list.add(new People("李四","女",23)); list.add(new People("王五","男",26)); list.add(new People("赵六","女",21)); Collections.sort(list,new People());
3.匿名Comparator
List list = new ArrayList<>();
list.add(new People("张三","男",21));
list.add(new People("李四","女",23));
list.add(new People("王五","男",26));
list.add(new People("赵六","女",21));
Collections.sort(list,new Comparator(){
@Override
public int compare(People o1, People o2) {
if(o1.getAge()>o2.getAge()){
return 1;
}else if(o1.getAge() == o2.getAge()){
return 0;
}else {
return -1;
}
}
});
3.数组常用Stream(jdk1.8)
数组过滤
list = list.stream().filter((item)->item.getAge()>22).collect(Collectors.toList());
过滤年龄大于22。
数组值存在判断boolean flag = list.stream().anyMatch((item)->item.getAge()==26);
数组中若存在age值为26时,返回true,若没有返回false
数组值全匹配判断boolean flag = list.stream().allMatch((item)->item.getAge()>0);
数组中的age值都大于0时返回true,否则返回false
去重list = list.stream().distinct().collect(Collectors.toList());
若是对象数组,需要重写对象中的equals和Hashcode方法;
持续更新,欢迎指正。



