[英]Arduino Map equivalent function in Java
Is there a function similar to the Map function in Arduino for Java? 是否有类似于Arduino for Java中的Map函数的函数?
I need to map a range of values to another range of values, so I was wondering if there was something similar to it in Java, I've been searching but I only get the Java's Map function. 我需要将一系列值映射到另一个值范围,所以我想知道在Java中是否有类似的东西,我一直在搜索,但我只获得了Java的Map函数。
The code of map()
from Arduino's library is this: 来自Arduino库的map()
代码如下:
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}
This will work in Java just the same - no real magic. 这将在Java中起作用 - 没有真正的魔力。 But standard Java has nothing predefined like this. 但标准Java没有像这样预定义。
Uh, Java doesn't have a 'Map' function, it has a Map type in the Collections (java.util), with multiple implementations. 呃,Java没有'Map'函数,它在Collections(java.util)中有一个Map类型,有多个实现。 But this is just a storage mechanism, basically resulting in key=>value pairs. 但这只是一种存储机制,基本上会产生key =>值对。 Based on my reading of the Arduino docs you linked, you'd need to implement your own method to map the value appropriately. 根据我对您链接的Arduino文档的阅读,您需要实现自己的方法来适当地映射值。
You could do something like this: 你可以这样做:
Map<K,V> mapValues(Collection<K> keys, Collection<V> values) {
if(keys.size() != values.size()) throw new ... // pick your poison there
Map<K,V> map = new HashMap<K,V>();
Iterator<K> keyIter = keys.iterator();
Iterator<V> valIter = values.iterator();
while(keyIter.hasNext()) {
K key = keyIter.next();
V val = valIter.next();
map.put(key,val);
}
return map;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.