基于输入参数类型的动态返回类型
我正在尝试编写一个小函数,该功能根据另一个元素进行两个列表,并根据另一个元素进行分类。因此,类似:
List<Integer> keys = Arrays.asList(3, 5, 2, 4, 1);
List<String> valuesToSort = Arrays.asList("A", "B", "C", "D", "E");
List<String> sortedValues = sort(keys, valuesToSort);
将导致排序列表[E,C,A,D,B]
。
但是,valuestosort
可能是不同事物的列表,例如整数,浮点或其他列表。理想情况下,我希望我的程序获取我投入的任何列表,根据键
对其进行排序,然后返回与输入相同类型的列表。我该怎么做?如果修复了值的类型
,则排序本身将很简单,例如
public List<String> sort(List<Integer> keys, List<String> values){
Multimap<Integer, String>> multiMap = LinkedListMultimap.create();
for (int i = 0; i < keys.size(); i++) {
multiMap.put(keys.get(i), values.get(i));
}
List<String>> sortedValues = Lists.newArrayList();
for (Integer key : Ordering.natural().sortedCopy(multiMap.keys())) {
for (String value : multiMap.get(key)) {
sortedValues.add(value);
}
}
return sortedValues;
}
,仅当value
是预期类型的列表时才有效。
I'm trying to write a small function that takes two lists and sorts one based on the elements of the other. So something like:
List<Integer> keys = Arrays.asList(3, 5, 2, 4, 1);
List<String> valuesToSort = Arrays.asList("A", "B", "C", "D", "E");
List<String> sortedValues = sort(keys, valuesToSort);
would result in a sorted list [E, C, A, D, B]
.
However, valuesToSort
might be a list of something different, like integers, floats or other lists. Ideally, I would want my program to take any list I throw at it, sort it according to keys
, and then return a list of the same type as the input. How would I do that? If the type of values
were fixed, the sorting itself would be straightforward, like for example
public List<String> sort(List<Integer> keys, List<String> values){
Multimap<Integer, String>> multiMap = LinkedListMultimap.create();
for (int i = 0; i < keys.size(); i++) {
multiMap.put(keys.get(i), values.get(i));
}
List<String>> sortedValues = Lists.newArrayList();
for (Integer key : Ordering.natural().sortedCopy(multiMap.keys())) {
for (String value : multiMap.get(key)) {
sortedValues.add(value);
}
}
return sortedValues;
}
but this only works if values
is a list of the expected type.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用泛型来实现此目的,如下所示:
现在,当您传递字符串列表时,泛型
T
将被视为String
。当您传递整数列表时,T
将变为Integer
。这将在运行时发生。You can use Generics for this as follow:
Now, when you pass list of strings, the generic
T
would be considered asString
. When you pass list of integers,T
would becomeInteger
. This will happen at runtime.这是一种方法。我假设这些键可能有重复的数字,例如
[3, 5, 2, 2, 1]
。否则,更简单的算法将占上风。keys
列表对从0 到keys.size()
的值进行排序[4 2 0 3 1]
打印
通用方法
T
Integer
类型Here is one way. I am presuming that the keys could have duplicate numbers like
[3, 5, 2, 2, 1]
. Otherwise, simpler algorithms would prevail.0 to keys.size()
using thekeys
list[4 2 0 3 1]
prints
The generic method
T
Integer