假设如下:
String example = "something";
String firstLetter = "";
在分配 firstLetter的以下方法中,是否有可能影响性能的差异需要注意;
firstLetter = String.valueOf(example.charAt(0));
firstLetter = Character.toString(example.charAt(0));
firstLetter = example.substring(0, 1);
返回第一个字母为 String的原因是,这是在 Hadoop 中运行的,并且需要将一个字符串赋值给 Text类型,firstLetter将从 map()方法中作为 key输出,例如:
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);
}
}
}
}