1、sort工具类
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
*
* @author 木此
*/
public class SortUtils {
public static Map<String,Integer> map = new HashMap<>(16);
//自定义顺序 也可以通过查询DB来put值
static {
map.put("刘备",1);
map.put("关羽",2);
map.put("张飞",3);
map.put("吕布",4);
map.put("#测试",5);
}
//排序方法
public static List<TestObject> sort(List<TestObject> testObjects){
List<TestObject> sorted = testObjects.stream()
.sorted(Comparator.comparingInt(TestObject::testSort)).collect(Collectors.toList());
return sorted;
}
//提供给类的获取排序位数方法
public static int getSort(String brand){
return map.get(brand);
}
}
2、测试对象
/**
*
* @author 木此
*/
public class TestObject {
/**
* 品牌
*/
private String brand;
private String other;
private String test;
//获取排序位数方法
public int testSort(){
return SortUtils.getSort(this.brand);
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getOther() {
return other;
}
public void setOther(String other) {
this.other = other;
}
public String getTest() {
return test;
}
public void setTest(String test) {
this.test = test;
}
@Override
public String toString() {
return "TestObject{" + "brand='" + brand + '\'' + ", other='" + other + '\'' + ", test='"
+ test + '\'' + '}';
}
}
3、测试方法
/**
*
* @author 木此
*/
public class SortTest {
@Test
public void main() {
List<TestObject> testObjects = new ArrayList<>();
buildData(testObjects,"张飞",1);
buildData(testObjects,"关羽",2);
buildData(testObjects,"吕布",3);
buildData(testObjects,"张飞",4);
buildData(testObjects,"刘备",5);
buildData(testObjects,"#测试",6);
System.out.println(testObjects.toString());
List<TestObject> sort = SortUtils.sort(testObjects);
System.out.println("---------------------------------------");
System.out.println(sort.toString());
}
private void buildData(List<TestObject> testObjects,String brand,int number) {
TestObject testObject = new TestObject();
testObject.setBrand(brand);
testObject.setOther("test"+number);
testObject.setTest("test"+number);
testObjects.add(testObject);
}
}
4、测试结果
[TestObject{brand='张飞', other='test1', test='test1'},
TestObject{brand='关羽', other='test2', test='test2'},
TestObject{brand='吕布', other='test3', test='test3'},
TestObject{brand='张飞', other='test4', test='test4'},
TestObject{brand='刘备', other='test5', test='test5'},
TestObject{brand='#测试', other='test6', test='test6'}]
-----------------------------------------------------------
[TestObject{brand='刘备', other='test5', test='test5'},
TestObject{brand='关羽', other='test2', test='test2'},
TestObject{brand='张飞', other='test1', test='test1'},
TestObject{brand='张飞', other='test4', test='test4'},
TestObject{brand='吕布', other='test3', test='test3'},
TestObject{brand='#测试', other='test6', test='test6'}]