简体   繁体   English

如何在Java中对通配符列表进行排序

[英]How to sort a wild card List in Java

I am new to Java Streams and i want to sort a list. 我是Java Streams的新手,我想对列表进行排序。 The list is of type: 列表的类型为:

List<? extends PositionType> positions

I want to sort this list on the basis of a field that we get on casting each PositionType object to a subclass ConvertedPosition in ascending order. 我想根据将每个PositionType对象按升序ConvertedPosition为子类ConvertedPosition得到的字段对该列表进行排序。

So far i have tried this: 到目前为止,我已经尝试过了:

List<ConvertedPosition> sortedPositions = positions.stream()
                .sorted(Comparator.comparingInt(((ConvertedPosition)PositionType::getPnlSpn()))
                .collect(Collectors.toList());

But i am getting compilation error: 但是我收到编译错误:

The method comparingInt(ToIntFunction<? super T>) in the type Comparator is not applicable for the arguments (ConvertedPosition)
The target type of this expression must be a functional interface

I would highly discourage the current attempt utilizing type casting. 我强烈不鼓励当前使用类型转换的尝试。 What if there is an item in your list that is not of type ConvertedPosition ? 如果您的列表中有一个不是ConvertedPosition类型的项目怎么办?

If it is feasible to discard items that are not of type ConvertedPosition , then I would propose the following extension of the presented code: 如果可以丢弃不是ConvertedPosition类型的项目是可行的,那么我建议对所提供的代码进行以下扩展:

List<ConvertedPosition> sortedPositions = positions.stream()
    .filter(e -> e instance ConvertedPosition) // filter out all non-ConvertedPosition items
    .map(e -> (ConvertedPosition) e)           // cast is safe due to the previous filter
    .sorted(Comparator.comparingInt(PositionType::getPnlSpn()))
    .collect(Collectors.toList());

Ideone example (1) Ideone示例(1)

If discarding non- ConvertedPosition items is not an option, there is also the possibility of writing some kind of converter. 如果不能丢弃非ConvertedPosition项,则还可以编写某种转换器。 Yon can find a sample solution in this Ideone example (2) . 在此Ideone示例(2)中, Yon可以找到示例解决方案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM