Java Array 根据子类中的变量对对象列表进行排序
Java Array Order a Object List as per the variable in subclasses
我有一个父 Class“内容”,其中有两个子class“文档”和“评估”。
@Document(collection = "content")
public class Content {
@Id
private String id;
private String name;
//this type is from enum
private Type type;
}
public enum Type {
DOCUMENT,
ASSESSMENT
}
public class Document extends Content {
private String priority;
}
public class Assessment extends Content {
private String priority;
}
public interface ContentRepository extends MongoRepository<Content, String> {
Page<Content> findAllByTypeIn(List<Type> types, Pageable pageable);
}
在服务层我得到内容列表。
Pageable pageable = PageRequest.of(page, size);
List<Type> typeList = Arrays.asList(Type.DOCUMENT, Type.ASSESSMENT);
Page<Content> contents = contentRepository.findAllByTypeIn(typeList , pageable);
List<Content> contents = contents.getContent();
**//need to order this List**
在这里,我得到了类型为 DOCUMENT 或 ASSESSMENT 的内容列表。我需要根据优先级排序此列表。注意:优先级在两个subclasses中。我无法将其移至超级 class,因为该父 class 的子 class 没有此 'priority' 变量。
我会说为包含 priority
的 classes 创建另一个中间抽象。根据设计标准,这也是正确的。这样您就可以轻松地使用该字段对其进行排序。
类似 PriorityContent
class 的扩展 Content
。 Document
和 Assessment
将扩展 PriorityContent
而不是 Content
.
我有一个父 Class“内容”,其中有两个子class“文档”和“评估”。
@Document(collection = "content")
public class Content {
@Id
private String id;
private String name;
//this type is from enum
private Type type;
}
public enum Type {
DOCUMENT,
ASSESSMENT
}
public class Document extends Content {
private String priority;
}
public class Assessment extends Content {
private String priority;
}
public interface ContentRepository extends MongoRepository<Content, String> {
Page<Content> findAllByTypeIn(List<Type> types, Pageable pageable);
}
在服务层我得到内容列表。
Pageable pageable = PageRequest.of(page, size);
List<Type> typeList = Arrays.asList(Type.DOCUMENT, Type.ASSESSMENT);
Page<Content> contents = contentRepository.findAllByTypeIn(typeList , pageable);
List<Content> contents = contents.getContent();
**//need to order this List**
在这里,我得到了类型为 DOCUMENT 或 ASSESSMENT 的内容列表。我需要根据优先级排序此列表。注意:优先级在两个subclasses中。我无法将其移至超级 class,因为该父 class 的子 class 没有此 'priority' 变量。
我会说为包含 priority
的 classes 创建另一个中间抽象。根据设计标准,这也是正确的。这样您就可以轻松地使用该字段对其进行排序。
类似 PriorityContent
class 的扩展 Content
。 Document
和 Assessment
将扩展 PriorityContent
而不是 Content
.