简体   繁体   中英

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. 在此处输入图像描述

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);

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM