Steven Oh
Steven Oh

Reputation: 394

Shuffling groups of elements in an arraylist

I am working on a group generator and currently I am making an ArrayList from this txt file. enter image description here

So that, the ArrayList is in the form of [PedroA, Brazil, Male, 10G, Saadia...]

I want to shuffle 4 elements at a time, to randomize this arraylist.

I am storing the info in

ArrayList<String> studentInfo = info.readEachWord(className);

Upvotes: 0

Views: 114

Answers (1)

rzwitserloot
rzwitserloot

Reputation: 102903

This is very hard to do. It's possible, of course, but difficult.

It is being made difficult because what you want to do is bizarre.

The normal way to do this would be to:

  1. Make a class representing a single entry, let's call it class Person.
  2. Read this data by parsing each line into a single Person instance, and add them all to a list.
  3. Just call Collections.shuffle(list); to shuffle them.

If we have the above, we could do what you want, by then converting your List<Person> back into a List<String>. In many ways this is the simplest way to do the task you ask for, but then you start wondering why you want this data in the form of a list of strings in the first place.

enum Gender {
    MALE, FEMALE, OTHER;

    public static Gender parse(String in) {
        switch (in.toLowerCase()) {
        case "male": return MALE;
        case "female": return FEMALE;
        default: return OTHER;
    }
}

class Person {
    String name;
    String location;
    Gender gender;
    [some type that properly represents whatever 10G and 10W means];

    public static Person readLine(String line) {
        String[] parts = line.split("\\s+", 4);
        Person p = new Person();
        p.name = parts[0];
        p.location = parts[1];
        p.gender = Gender.parse(parts[2]);
        ...;
        return p;
    }
}

you get the idea.

Upvotes: 1

Related Questions