user3225573 user3225573 -4 years ago 121
Java Question

Java Randomly Select 10 rows from 100 rows in CSV

I am working on a Java program and I have a data.csv file with 100 rows. I want to randomly select 10 rows. The Data looks like this:

T1 T2 T3 T4 T5
1 1.0 1 0 1
1 1.0 0 0 1
0 0.0 1 1 0


I have managed to read in the CSV file using the following code:

public static void main(String[] args) throws IOException {
try
{
Scanner readIn = new Scanner (new File ("data.csv") );
while ( readIn.hasNext() )
{
line = readIn.nextLine();
str = line.split(",",-1);
}
readIn.close();
}
catch (ArrayIndexOutOfBoundsException ob)
{
System.out.println("File not found..." );
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
}

Answer Source

Try this

int j=0;
    while(j!=10)
    {
        SecureRandom random = new SecureRandom(); 
        int row = random.nextInt(list.size()); 
        System.out.println("Row "+row+"="+list.get(row));
        j++;
    }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download