从arraylist制作arraylists

时间:2013-09-20 18:42:34

标签: java arraylist

我有一个通过导入文件制作的arraylist。我现在想按类别将此列表分成较小的arraylists。我对原始arraylist的代码如下:

public class TriviaGamePlayer {

public static void main(String[] args) throws IOException {
File gameFile = new File("trivia.txt");

List<TriviaGame> triviaQuestions = new ArrayList<TriviaGame>();
Scanner infile = new Scanner(gameFile);
String lastKnownCategory = "";

while (infile.hasNextLine()) {
    String currentLine = infile.nextLine();

    if (!currentLine.isEmpty()) {
        TriviaGame currentQuestion = new TriviaGame();

        if (currentLine.endsWith("?")) {
            currentQuestion.setCategory(lastKnownCategory);
            currentQuestion.setQuestion(currentLine);
            currentQuestion.setAnswer(infile.nextLine());
        } else {
            currentQuestion.setCategory(currentLine);
            currentQuestion.setQuestion(infile.nextLine());
            currentQuestion.setAnswer(infile.nextLine());
            lastKnownCategory = currentLine;
        }
        triviaQuestions.add(currentQuestion);
    }
}

infile.close();



System.out.println(triviaQuestions);

这将显示[category = Arts&amp;文学,问题=传统上用于演奏的邦戈鼓是什么?,答案=膝盖]在不同的类别中有更多的跟随它。从这里开始,我想为每个类别制作不同的arraylists,并能够选择类别,问题和答案。 感谢

1 个答案:

答案 0 :(得分:1)

尝试这样做:

public class TriviaGamePlayer {

static class TriviaGame {
  String category;
  String question;
  String answer;
}

public static void main(String[] args) throws IOException {
File gameFile = new File("trivia.txt");

List<TriviaGame> triviaQuestions = new ArrayList<TriviaGame>();
Scanner infile = new Scanner(gameFile);
String lastKnownCategory = "";
Map<String, List<TriviaGame>> map = new HashMap<String, List<TriviaGame>>();

while (infile.hasNextLine()) {
    String currentLine = infile.nextLine();

    if (!currentLine.isEmpty()) {
        TriviaGame currentQuestion;
        if(map.containsKey(lastKnownCategory) == false)
          map.put(lastKnownCategory, new ArrayList<TriviaGame>());

        map.get(lastKnownCategory).add(currentQuestion = new TriviaGame());

        if (currentLine.endsWith("?")) {
            currentQuestion.setCategory(lastKnownCategory);
            currentQuestion.setQuestion(currentLine);
            currentQuestion.setAnswer(infile.nextLine());
        } else {
            currentQuestion.setCategory(currentLine);
            currentQuestion.setQuestion(infile.nextLine());
            currentQuestion.setAnswer(infile.nextLine());
            lastKnownCategory = currentLine;
        }
        triviaQuestions.add(currentQuestion);
    }
}

  infile.close();

  System.out.println(map);
  }
}

基本上你甚至可以删除triviaQuestions.add(currentQuestion);并引用地图。在地图中,您将按lastKnownCategory值分组所有问题。