我有以下方法,它接受 CustomClass 列表并使用流执行过滤器,并根据过滤器的结果在每一步返回。
我想知道是否有一种方法可以简化代码,但将过滤器和语句组合在一起,使其更加简洁和高效。
public String transform(List<CustomObject> listOfObjects) {
listOfObjects = listOfObjects.stream()
.filter(object -> object.objectType().equals("BUSINESS")).toList();
// Primary check as all object should be of business type
// and if nothing exist we throw an exception
if (listOfObjects.isEmpty()) {
throw new RuntimeException("NO BUSINESS OBJECT FOUND");
}
// All objects are now of business type but we want them to be active
List<CustomObject> listOfActiveObjects = listOfObjects.stream()
.filter(object -> object.objectStatus().equals("ACTIVE"))
.toList();
// If no active object found just return the first business object sorted url
if (listOfActiveObjects.isEmpty()) {
return listOfObjects.stream()
.sorted(Comparator.comparing(CustomObject::url))
.toList().get(0).getUrl();
}
// Active objects are present so now filtered with proper locale
List<CustomObject> listOfActiveObjectsWithLocale = listOfActiveObjects.stream()
.filter(object -> object.locale().equals("en-US"))
.toList();
// If no locale was found just return the first sorted business active url
if (listOfActiveObjectsWithLocale.isEmpty()) {
return listOfActiveObjects.stream()
.sorted(Comparator.comparing(CustomObject::url))
.toList().get(0).getUrl();
}
// All filters applied, so within these objects return the sorted business/active/locale url
return listOfActiveObjectsWithLocale.stream()
.sorted(Comparator.comparing(CustomObject::url))
.toList().get(0).getUrl();
}
为了使其不那么复杂,您可以将过滤器与可选类一起使用。这将处理过滤过程中未找到对象的情况。
使用Java Streams内置的过滤器功能可以顺利地处理流,过滤后可以使用map函数并调用findFirst()作为故障转移机制,您可以使用orElseGet()函数
请参阅以下有关 Oracle Stream API 的官方 Oracle 指南。
https://www.oracle.com/technical-resources/articles/java/ma14-java-se-8-streams.html
https://docs.oracle.com/javase/8/docs/api/java/util/Optional.html