Home > Software engineering >  How can I generated a list of data then query into the list?
How can I generated a list of data then query into the list?

Time:06-30

I am new to Java and I am trying to build a Java command-line program, which generates random dataset (as in getData()) and query into the generated dataset. But I don't know how to pass the generated data from getData() function to the main function so that I can find the oldest person in my generated data.

public class Data {

    public String first;
    public String last;
    public int age;
    public int id;
    public String country;

    public Data(String first, String last, int age, int id, String country) {
        this.first = first;
        this.last = last;
        this.age = age;
        this.id = id;
        this.country = country;

    }

    public String toString() {
        return "{"  
                " 'firstName': "   first   ","  
                " 'lastName': "   last   ","  
                " 'age': "   age   ","  
                " 'id': "   id   ","  
                " 'country': "   country  
                " }";
    }

    public static ArrayList<Data> getData(int numRows) {
        ArrayList<Data> generator = new ArrayList<>();

        String[] names = {"James", "Matt", "Olivia", "Liam", "Charlotte", "Amelia", "Evelyn", "Taeyeon", "Sooyoung", "Tiffany", "Yoona", "Hayley"};
        String[] lastName = {"Novak", "Forbis", "Corner", "Broadbet", "Kim", "Young", "Hwang", "Choi", "McDonalds", "Kentucky", "Holmes", "Shinichi"};
        String[] country = {"New Zealand", "Vietnam", "Korea", "French", "Japan", "Switzerland", "Italy", "Spain", "Thailand", "Singapore", "Malaysia", "USA"};
        String data = "";
        Random ran = new Random();

        int namesLength = numRows; // passing length to names_len
        int lastNameLength = lastName.length; // passing length to lastname_len
        int countryLength = country.length; // passing length to lastname_len

        for (int i = 0; i < numRows; i  ) { // for loop to iterate upto names.length
            int x = ran.nextInt(namesLength); // generating random integer
            int y = ran.nextInt(lastNameLength); // generating random integer
            int z = ran.nextInt(countryLength);
            int a = ran.nextInt(40);
            int exampleId = ran.nextInt(1000);

            // below for loop is to remove that element form names array
            for (int j = x; j < (namesLength - 1); j  ) {
                names[j] = names[j   1]; // this moves elements to one step back
            }
            // below for loop is to remove that element form Lastnames array
            for (int j = y; j < (lastNameLength - 1); j  ) {
                lastName[j] = lastName[j   1]; // this moves elements to one step back
            }

            for (int j = z; j < (countryLength - 1); j  ) {
                country[j] = country[j   1]; // this moves elements to one step back
            }

            namesLength = namesLength - 1; // reducing len of names_len by 1
            lastNameLength = lastNameLength - 1; // reducing len of lastname_len by 1
            countryLength = countryLength - 1; // reducing len of lastname_len by 1

            // Output data in NDJSON format
            data = "{"  
                    " 'firstName': "   names[x]   ","  
                    " 'lastName': "   lastName[y]   ","  
                    " 'age': "   a   ","  
                    " 'id': "   exampleId   ","  
                    " 'country': "   country[z]  
                    " }";
            System.out.println(data);
// How can I add data to the generator list, the generator.add(data) does not work

        }
        // return a list of data
        return generator; 

    }

    public static void main(String[] args) {
        // Generate random data
        int rows = 0;
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter number of rows (maximum 12) you want to generate: ");
        rows = sc.nextInt();
        while (rows >= 13 || rows <= 0) {
            System.out.println("Rows must be in range of 1 and 12");
            System.out.print("Please reenter the number of rows: ");
            rows = sc.nextInt();
        }

        System.out.println("Data is now generated");

        ArrayList<Data> generatedData = getData(rows);


        String[] base_options = {
                "1 - Find the oldest person",
                "2 - Group by country and return count",
                "3 - Choose a country and group by age range",
                "4 - Find the youngest person",
        };
        System.out.println(base_options);


        // Task 2
        // TODO: PASTE GENERATED DATA INTO THIS

        // Find oldest
        Data oldest = generatedData.stream().max((a,b) -> a.age - b.age).get();
        System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));

CodePudding user response:

generator.add(new Data(names[x], lastName[y], a, exampleId, country[z])); works for me just fine

CodePudding user response:

You can parse your generated data in string to Data and get the max valud like this:

public static void main(String[] args) {
    // Generate random data
    int rows = 0;
    Scanner sc = new Scanner(System.in);
    System.out.print("Enter number of rows (maximum 12) you want to generate: ");
    rows = sc.nextInt();
    while (rows >= 13 || rows <= 0) {
        System.out.println("Rows must be in range of 1 and 12");
        System.out.print("Please reenter the number of rows: ");
        rows = sc.nextInt();
    }

    System.out.println("Data is now generated");

    ArrayList<String> generatedData = getData(rows);
    // Find oldest
    Data oldest = generatedData
        .stream()
        .map(it -> extractData(it))
        .max(Comparator.comparingInt(a -> a.age))
        .get();
    System.out.println(String.format("The oldest person is %s %s", oldest.first, oldest.last));
}

private static Data extractData(String str) {
    return new Data(
        extractProperty(str, "firstName"),
        extractProperty(str, "lastName"),
        Integer.parseInt(extractProperty(str, "age")),
        Integer.parseInt(extractProperty(str, "id")),
        extractProperty(str, "country")
    );
}

private static String extractProperty(String str, String keyName) {
    String key = "'"   keyName   "': ";
    int startIndex = str.indexOf(key)   key.length();
    if (startIndex < 0) {
        return "";
    }
    StringBuilder value = new StringBuilder();
    for (int i = startIndex ; i < str.length() ;   i) {
        char ch = str.charAt(i);
        if (ch == ',') {
            break;
        }
        value.append(ch);
    }
    return value.toString();
}
  • Related