Is there a way to convert Text to an int?

Refresh

March 2019

Views

1.9k time

1

The code that is giving me trouble is converting my content in the Text(), to an int so that I could use some arithmetic. I know how to convert a string to an int, but for some reason Hadoop needs to read items in a file as a TExt(). I can't find a method to do this conversion. ANy ideas on how this could be done?

    package BaseballStats;
    import java.io.IOException;
    import java.util.Iterator;

    import mrtools.CountMap;
    import mrtools.NBest;

    import org.apache.hadoop.io.Text;
    import org.apache.hadoop.mapred.MapReduceBase;
    import org.apache.hadoop.mapred.OutputCollector;
    import org.apache.hadoop.mapred.Reducer;
    import org.apache.hadoop.mapred.Reporter;

    public class StatReducer extends MapReduceBase
    implements Reducer<Text, Text, Text, Text[]> {

        private Text Hits = new Text(); 
        private Text AtBats = new Text();
        //private Text Year = new Text();   
        int totalAtBats = 0;
        int totalHits = 0;
        float average = 0;
        Text [] Pair = {AtBats, Hits};

        public void reduce(Text key, Iterator<Text> values,
                        OutputCollector<Text, Text[]> output,
                        Reporter reporter) throws IOException {

            //Need to pull values from the Array and assign to AtBats    
            //THen total all at bats and hits per year (key)

            //Divide hits by at Bats to get batting average
            //Output batting average per year

            for (Text s: Pair) {           
                //Do your stuff here

                Pair[0] = AtBats;
                Pair[1] = Hits;
            }
            //Get values to key to sum up and get a total per year.
            while (values.hasNext()){
                int AB = Integer.parseInt(AtBats);
                int i = Integer.valueOf(AtBats);

                totalAtBats = AB + totalAtBats;

            }
        }
    }

1 answers

2

You could first convert the Text to a string using the .toString() method and then convert the result to an int.