java基础回顾:排序接口 - Comparator Comparable
需求:将Bean 按照给定的字符串顺序排序,不在这其中的字符串排序到最末尾
假定给定字符串序列为: String[] contents = {"PZ1, "PZ2", "PZ3", "OS1"}
@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
public class TestBean implements Comparable<TestBean> {
private String property;
@Override
public int compareTo(TestBean o) {
if (this == o) {
return 0;
}
if (o == null || !StringUtils.hasText(o.getProperty)) {
return 1;
}
List<String> strings = Arrays.asList("OS1", "PZ3", "PZ2", "PZ1");
String anotherProperty = o.property;
int i = strings.indexOf(property);
int i1 = strings.indexOf(anotherProperty);
return i - i1;
}
简单测试,不写测试用例了
public static void main(String[] args) {
TestBean testBean = new TestBean("PZ1");
TestBean testBean1 = new TestBean("PZ2");
TestBean testBean2 = new TestBean("PZ3");
TestBean testBean3 = new TestBean("PZ1");
TestBean testBean4 = new TestBean("PZ2");
TestBean testBean5 = new TestBean("PZ2");
TestBean testBean6 = new TestBean("OTHER");
TestBean testBean7 = new TestBean("MNR1");
TestBean testBean8 = new TestBean("OS1");
List<TestBean> testBeans = Arrays.asList(testBean, testBean1, testBean2, testBean3, testBean4, testBean5, testBean6, testBean7, testBean8);
testBeans.stream().sorted(Comparator.reverseOrder()).map(TestBean::getProperty).forEach(System.out::println);
}
}
···