假设如下:
String example = "something";
String firstLetter = "";
以下分配方式是否存在firstLetter
可能影响性能的差异?哪个最好,为什么?
firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);
第一个字母作为 a 返回的原因是String
它正在 Hadoop 中运行,并且需要一个字符串来分配给一个Text
类型,firstLetter
它将作为key
一个map()
方法输出,例如:
public class FirstLetterMapper extends Mapper<LongWritable, Text, Text, IntWritable> {
String line = new String();
Text firstLetter = new Text();
IntWritable wordLength = new IntWritable();
@Override
public void map(LongWritable key, Text value, Context context)
throws IOException, InterruptedException {
line = value.toString();
for (String word : line.split("\\W+")){
if (word.length() > 0) {
// ---------------------------------------------
// firstLetter assignment
firstLetter.set(String.valueOf(word.charAt(0)).toLowerCase());
// ---------------------------------------------
wordLength.set(word.length());
context.write(firstLetter, wordLength);
}
}
}
}