DateSet的API详解三
getType
def getType(): TypeInformation[T]
Returns the TypeInformation for the elements of this DataSet.
获取DataSet的元素的类型信息
执行程序:
//1.创建一个 DataSet其元素为String类型
val input: DataSet[String] = benv.fromElements("A", "B", "C")
//2.获取DataSet的元素的类型信息
input.getType
执行结果:
res89: org.apache.flink.api.common.typeinfo.TypeInformation[String] = String
map
def map[R](fun: (T) ⇒ R)(implicit arg0: TypeInformation[R], arg1: ClassTag[R]): DataSet[R]
def map[R](mapper:MapFunction[T,R])(implicit arg0:TypeInformation[R],arg1:ClassTag[R]):DataSet[R]
Creates a new DataSet by applying the given function to every element of this DataSet.
将一个DataSet转化成另一个DataSet。转化操作对每一个元素执行一次。
map示例一
执行程序:
//1.创建一个DataSet其元素为Int类型
val input: DataSet[Int] = benv.fromElements(23, 67, 18, 29, 32, 56, 4, 27)
//2.将DataSet中的每个元素乘以2
val result=input.map(_*2)
//3.将DataSet中的每个元素输出出来
result.collect
执行结果:
res47: Seq[Int] = Buffer(46, 134, 36, 58, 64, 112, 8, 54)
web ui中的执行效果:
map示例二
执行程序:
//1.创建一个DataSet[(Int, Int)]
val intPairs: DataSet[(Int, Int)] = benv.fromElements((18,4),(19,5),(23,6),(38,3))
//2.键值对的key+value之和生成新的dataset
val intSums = intPairs.map { pair => pair._1 + pair._2 }
//3.显示结果
intSums.collect
执行结果:
res44: Seq[Int] = Buffer(22, 24, 29, 41)
web ui中的执行效果:
flatMap
def flatMap[R](fun:(T)⇒
TraversableOnce[R])(implicit arg0:TypeInformation[R],arg1:ClassTag[R]):DataSet[R]
def flatMap[R](fun:(T, Collector[R])⇒
Unit)(implicit arg0:TypeInformation[R],arg1:ClassTag[R]):DataSet[R]
def flatMap[R](flatMapper:FlatMapFunction[T,R])
(implicit arg0:TypeInformation[R],arg1:ClassTag[R]):DataSet[R]
Creates a new DataSet by applying the given function to every element and flattening the results.
flatMap示例一
执行程序:
//1.创建一个 DataSet其元素为String类型
val input: DataSet[String] = benv.fromElements("zhangsan boy", "lisi girl")
//2.将DataSet中的每个元素用空格切割成一组单词
val result=input.flatMap { _.split(" ") }
//3.将这组单词显示出来
result.collect
执行结果:
res46: Seq[String] = Buffer(zhangsan, boy, lisi, girl)
web ui中的执行效果:
flatMap示例二
执行程序:
//1.创建一个DataSet其元素为String类型
val textLines: DataSet[String] =benv.fromElements(
"this is a good job!",
"you can do a lot of things!",
"flink is a framework for bigdata.")
//2.对每句话进行单词切分
val words = textLines.flatMap { _.split(" ") }
//3.显示结果内容
words.collect
执行结果:
res48: Seq[String] = Buffer
(this, is, a, good, job!,
you, can, do, a, lot, of, things!,
flink, is, a, framework, for, bigdata.)
web ui中的执行效果: