java - Transfer data from List to a 2D array -
i have java code extract unique word string containing several sentences , counting occurences of word in each sentence.
this java coding used achieve that. alternately, may try here.
import java.util.*; class main { public static void main(string[] args) { string sometext = "lorem ipsum dummy text of printing , typesetting industry. lorem ipsum has been industry's standard dummy text ever since 1500s, when unknown printer took galley of type , scrambled make type specimen book. has survived not 5 centuries, leap electronic typesetting, remaining unchanged. popularised in 1960s release of letraset sheets containing lorem ipsum passages, , more desktop publishing software aldus pagemaker including versions of lorem ipsum."; list<list<string>> sort = new arraylist<>(); map<string, arraylist<integer>> res = new hashmap<>(); (string sentence : sometext.split("[.?!]\\s*")) { sort.add(arrays.aslist(sentence.split("[ ,;:]+"))); //put each sentences in list } int sentencecount = sort.size(); (list<string> sentence: sort) { sentence.stream().foreach(s -> res.put(s, new arraylist<integer>(collections.ncopies(sentencecount, 0)))); } int index = 0; (list<string> sentence: sort) { (string s : sentence) { res.get(s).set(index, res.get(s).get(index) + 1); } index++; } system.out.println(res); } } the output code this:
{standard=[0, 1, 0, 0], but=[0, 0, 1, 0], ..... } which means word 'standard' occured none sentence 1, 1 time in sentence 2, none in sentence 3 & 4.
however, data inside list. how convert data form of 2d matrix become this:
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 2d array named multi appreciate on this. thanks.
a loop inside loop should you. code assumes rows each have same number of elements (which should there's same number of possible sentences each word). i've added arraylist of keys, can reference them later know row index in matrix corresponds given word.
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]; (int rowindex = 0; rowindex < rowsize; rowindex++) { string key = keys.get(rowindex); list<integer> row = res.get(key); (int colindex = 0; colindex < colsize; colindex++) { multi[rowindex][colindex] = row.get(colindex); } } i made array doubles that's in question, seems ints more appropriate.
apologies previous version of answer; looking @ wrong object trying aggregate.
Comments
Post a Comment