首页 > 解决方案 > TStream 中的元组到底是什么?

问题描述

这是取自Apache Edgent 文档的代码

我不明白元组到底是什么。代码如下:

public static void main(String[] args) throws Exception {
    TempSensor sensor = new TempSensor();
    DirectProvider dp = new DirectProvider();
    Topology topology = dp.newTopology();

    TStream<Double> tempReadings = topology.poll(sensor, 1, TimeUnit.MILLISECONDS);
    TStream<Double> simpleFiltered = tempReadings.filter(tuple ->
            !optimalTempRangeRef.get().contains(tuple));
    simpleFiltered.sink(tuple -> System.out.println("Temperature is out of range! "
            + "It is " + tuple + "\u00b0F!"));

    tempReadings.print();

    dp.submit(topology);
}

我得到的错误是tuple cannot be resolved to a variable。我得到的错误到底是什么?谢谢你。

标签: javaapache-edgent

解决方案


TStream<T> 接口旨在模拟数据流,通常是传感器读数。在T这种情况下,是用于存储单个读数的类型,但“读数”实际上可以表示多个数字(例如温度、湿度和风速)组合成一个复合类型,这里通常称为“元组”的价值观。

但是,看看您的示例的上下文,我们正在处理一个简单的温度读数流,因此这里T对应于单个数字 type Double。所以选择“元组”作为变量名有点令人困惑(从数学上讲,它是一个1-tuple,但在这种情况下,它只是意味着“一个数字”)。

在您的代码中,该filter()方法采用predicate,这里是

tuple -> !optimalTempRangeRef.get().contains(tuple)

optimalTempRangeRef.get()返回 a Range(Double),所以谓词是说“我们的温度值是否超出了我们的最佳范围?”

从文档中Range

contains() is used to check for containment: e.g.

 Ranges.closed(2,4).contains(2);    // returns true
 Ranges.open(2,4).contains(2);      // returns false
 Ranges.atLeast(2).contains(2);     // returns true
 Ranges.greaterThan(2).contains(2); // returns false
 Ranges.atMost(2).contains(2);      // returns true
 Ranges.lessThan(2).contains(2);    // returns false

编辑:

看起来您的 IDE 在使用 Java 8 lambda 语法时遇到了问题,因此您可以使用匿名内部类重新编写代码,如下所示:

import org.apache.edgent.function.Predicate;
import org.apache.edgent.function.Consumer;


public static void main( String[] args ) throws Exception
{
    TempSensor sensor = new TempSensor();
    DirectProvider dp = new DirectProvider();
    Topology topology = dp.newTopology();

    TStream<Double> tempReadings = topology.poll( sensor, 1, TimeUnit.MILLISECONDS );
    TStream<Double> filteredStream = tempReadings.filter( new Predicate<Double>()
    {
        public boolean test( Double reading )
        {
            return !optimalTempRangeRef.get().contains( reading );
        }
    } );

    filteredStream.sink( new Consumer<Double>()
    {
        public void accept( Double reading )
        {
            System.out.println( "Temperature is out of range! "
                                + "It is " + reading + "\u00b0F!" )
        }
    } );

    tempReadings.print();

    dp.submit( topology );
}

推荐阅读