2

I read a text file that looks like this:

operationName1 Value

There is a variable number of lines, with different operations and corresponding value. I can read the file and get a 2D String array as the output. This is my code.

try{
    Path path = Paths.get("./myFile.txt");
    String[][] array = Files.lines(path)
                .map(s -> s.split("\\s+", 2))
                .map(a -> new String[]{a[0], a[1]})
                .toArray(String[][]::new);
    }catch(IOException e){  
}

Question: How could I change my code to get a 2d int array instead, where operationName1 would be "0" and operationName2 would be "1" (there is only two possible operation, each defined by a specific string)?

This text file:

operationOne 5
OtherOp 999
operationOne 8
operationOne 2

Would become that 2d int array:

[[0,5],[1,999],[0,8],[0,2]]

The index is important too. So the 1st line of the text file is the 1st line of my array.

PS: If there is a better syntax (a more recent one), I am open to suggestion.

Thank you very much.

David Gourde
  • 3,709
  • 2
  • 31
  • 65
  • Hey David, why not use the answer from the previous question and customize it? – Yassin Hajaj Mar 29 '16 at 20:22
  • You have the value in `a[0]`. Test what this value is and map it to the corresponding number either 0 or 1. – Alexis C. Mar 29 '16 at 20:28
  • Why are you trying to use streams here? Do you plan using parallelism? If not then probably simple loop would be much more readable (and probably little faster). – Pshemo Mar 29 '16 at 20:38

3 Answers3

4

If you need parallelism? ... this could be one approach

AtomicInteger atomicInteger = new AtomicInteger(0);
Map<String, Integer> known = new ConcurrentHashMap<>();
Path path = Paths.get("./myFile.txt");
int[][] array = Files.lines(path)
    .map(s -> s.split("\\s+", 2))
    .map(a -> new int[]{
        known.computeIfAbsent(a[0],
                k -> atomicInteger.getAndIncrement()),
        Integer.parseInt(a[1])
    })
    .toArray(int[][]::new);
Meiko Rachimow
  • 4,664
  • 2
  • 25
  • 43
1

I normally use the Scanner class for read text files

ArrayList<String[]> array = new ArrayList();
Scanner scan= new Scanner(new File("./myFile.txt"));
String str;
String auxiliary= new String[2];
while(scan.hasNextLine()){
    str= scan.readLine();
    auxiliary=str.split(" "); // you can use also the \\s
    for(int i=0; i<array.size();i++){
        if(array.get(i)[0].equals(auxiliary[0])){
           String  aux2[]={i,auxiliary[1]};
           break;
        }
   }
   String  aux2[]={array.size,auxiliary[1]};
}

I hope it helped.

# EDIT: Corrected some issues

  • Few problems: (1) Scanner doesn't return `null` when there are no more lines. It throws exception. So instead of `while(str!=NULL)` ((2) you probably meant `null` - Java is case-sensitive) you should use something like `while(scan.hasNextLine())`. (3) `split` expects string `" "` not char `' '` as argument. (Improvement) In most cases there is no need to use `split` when we have Scanner. We usually use `haveNext` or `haveNext*Type*` here if we know how many elements will appear in each line (we just need to use then `hasNext()` instead of `hasNextLine`). – Pshemo Mar 29 '16 at 20:52
  • Thanks. I have in the last 3 month worked hard in C, I have swapped some things. But I have fixed. – I'm just a poor boy Mar 29 '16 at 21:03
1

It is a bit long, but it allows you to go operationName1...operationNameN

I always try to keep the code clean, so if you have any questions just ask

public class Main {

    public static void main(String[] args) throws IOException {

            File file = new File("test.txt");
            BufferedReader bufferedReader = new BufferedReader(new FileReader(file));

            ArrayList<String> operations = new ArrayList<String>();
            ArrayList<Point> points = new ArrayList<Point>();

            String line;
            String[] array;

            int index;
            while((line = bufferedReader.readLine()) != null)
            {
                array = line.split(" ");

                if((index = hasOperation(array[0], operations)) == -1)
                {
                    operations.add(array[0]);
                    index = operations.size()-1;
                    points.add(new Point(index, Integer.parseInt(array[1])));
                }
                else
                {
                    points.add(new Point(index, Integer.parseInt(array[1])));
                }
            }

            System.out.print("[");
            for(int i = 0; i < points.size()-1; i++)
            {
                System.out.print(points.get(i).toString() + ",");
            }
            System.out.println(points.get(points.size()-1).toString()+"]");
    }



    public static int hasOperation(String operation, ArrayList<String> operations ){

        for(int index = 0; index < operations.size(); index++)
        {
            if(operation.equalsIgnoreCase(operations.get(index)))
                return index;
        }
        return -1;
    }

}

public class Point {
    public int x;
    public int y;


public Point(int x, int y){
        this.x = x;
        this.y = y;
    }

    @Override
    public String toString()
    {
        return "[" + x + "," + y + "]";
    }
}