2016-01-25 73 views
0

我有一個代碼將輸出來自List和Map的數據。我如何將相應的數字相乘?來自List和Map的Java乘法值

從列表

{prepare=0.25, saturday=0.5, republic=0.25, approach=0.25, ...} 

輸出的輸出從地圖

[0, 1, 0, 0,...] 

我需要讓他們有相應的數字相乘,總結起來。該總將是我想要的輸出這樣的:

(0.25*0)+(0.5*1)+(0.25*0)+(0.25*0).... = total 

這是我的示例代碼:

import java.util.*; 
import java.util.stream.Collectors; 

class WordOcc { 
    public static void main(String[] args) { 
    String someText = "hurricane gilbert head dominican coast saturday. hurricane gilbert sweep dominican republic sunday civil prepare high wind heavy rain high sea. storm approach southeast sustain wind mph mph. there alarm civil defense director a television alert shortly midnight saturday."; 

    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 
    } 

    // put all word in a hashmap with 0 count initialized 
    int sentenceCount = sort.size(); 

    for (List<String> sentence: sort) { 
     sentence.stream().forEach(x -> res.put(x, new ArrayList<Integer>(Collections.nCopies(sentenceCount, 0)))); 
    } 

    int index = 0; 
    // count the occurrences of each word for each sentence. 
    for (List<String> sentence: sort) { 
     for (String q : sentence) { 
      res.get(q).set(index, res.get(q).get(index) + 1); 
     } 
     index++; 
    } 


    Map<String,Float>word0List = getFrequency(res); 

    System.out.println(word0List + "\n"); //print the list value  

    //get first sentence count value from each word 
    List<Integer> sentence0List = getSentence(0, res); 

    System.out.println(sentence0List + "\n"); //print the map value 
    } 

    static List<Integer> getSentence(int sentence, Map<String, ArrayList<Integer>> map) { 
     return map.entrySet().stream().map(e -> e.getValue().get(sentence)).collect(Collectors.toList()); 
    } 

static Map<String, Float> getFrequency(Map<String, ArrayList<Integer>> stringMap) { 
    Map<String, Float> res = new HashMap<>(); 
stringMap.entrySet().stream().forEach(e -> res.put(e.getKey(), e.getValue().stream().mapToInt(Integer::intValue).sum()/(float)e.getValue().size())); 
     return res; 
     } 

} 

欣賞任何幫助。謝謝!

+0

這還不清楚。你能解釋一下當前代碼在做什麼,它應該做什麼以及它做錯了什麼? – Tunaki

+0

當前代碼沒有問題。我只是不確定如何將List和Map之間的值相乘。列表和地圖的當前輸出如前所述,並且我需要將它們相互乘以對應於它們的位置。 – Cael

+1

注意:一個HashMap沒有固有的順序,你也不應該期望一個。 –

回答

1

我不確定這是否是你正在尋找的,因爲沒有命令期望從評論中提到的哈希映射。但正如你所描述的你想要做這樣的事情:

float result = 0; 
Float[] hmValues = word0List.values().toArray(new Float[0]); 
for(int i = 0; i < word0List.size(); i++) 
    result += hmValues[i] * sentence0List.get(i); 
+0

有一點需要注意。始終圍繞代碼塊使用大括號是一種很好的做法。包括單行「if」表述或「for」循環。 – NotACleverMan