将数据从List传输到2D阵列

时间:2016-01-27 16:57:15

标签: java arrays matrix multidimensional-array

我有一个Java代码,它将从包含几个句子的字符串中提取一个唯一的单词,并计算每个句子中单词的出现次数。

这是用于实现该目的的Java编码。或者,您可以尝试here

import java.util.*;

class Main {
  public static void main(String[] args) {
    String someText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

    List<List<String>> sort = new ArrayList<>();
    Map<String, ArrayList<Integer>> res = new HashMap<>();

    for (String sentence : someText.split("[.?!]\\s*"))
    {
        sort.add(Arrays.asList(sentence.split("[ ,;:]+"))); //put each sentences in list
    }

    int sentenceCount = sort.size();
    for (List<String> sentence: sort) {
        sentence.stream().forEach(s -> res.put(s, new ArrayList<Integer>(Collections.nCopies(sentenceCount, 0))));
    }
    int index = 0;
    for (List<String> sentence: sort) {
        for (String s : sentence) {
            res.get(s).set(index, res.get(s).get(index) + 1);
        }
        index++;
    }
    System.out.println(res);
  }
}

代码的输出是这样的:

{standard=[0, 1, 0, 0], but=[0, 0, 1, 0], ..... }

这意味着&#39;标准&#39;发生的无是句子1,句子2中的1次,句子3中没有4.

但是,数据在List中。如何将数据转换为2D矩阵的形式,使其变得像这样:

    double[][] multi = new double[][]{
          { 0, 1, 0, 0 },
          { 0, 0, 1, 0 },
          { 0, 1, 0, 0 },
          { 0, 0, 1, 0 },
          { 0, 0, 1, 0 } } //data stored in a 2D array named multi

对此表示感谢。感谢。

1 个答案:

答案 0 :(得分:1)

循环中的循环应该可以。此代码假定每个行具有相同数量的元素(它们应该与每个单词的可能句子数相同)。我添加了一个键的ArrayList,以便您稍后可以引用它们以了解矩阵中的哪个行索引对应于给定的单词。

ArrayList<String> keys = new ArrayList<String>(res.keySet());
int rowSize = keys.size();
int colSize = res.get(keys.get(0)).size();
double [][] multi = new double[rowSize][colSize];
for (int rowIndex = 0; rowIndex < rowSize; rowIndex++) {
    String key = keys.get(rowIndex);
    List<Integer> row = res.get(key);
    for (int colIndex = 0; colIndex < colSize; colIndex++) {
        multi[rowIndex][colIndex] = row.get(colIndex);
    }
}

我让数组翻倍,因为这就是问题所在,但看起来更合适。

对此答案的先前版本表示歉意;我正在查看你想要聚合的错误对象。