Java turn linked hashmap to a string array

3.8k views Asked by At

I have a linkedhash map which has a key of the sentence number and the value the score of the sentence.

4=104
3=104
1=106
7=130
8=139
9=168
2=199
5=330

I need to keep it in this order because it is a text summiraztion program. I also have a array of string which contains each of the sentences which have been seperated using puncutation. How would I create a new string array which the first key will be sentence 4 corresponding to the first key in the linkedhash map. The last key in the array will be sentence 5.

Thanks

4

There are 4 answers

2
Raman Shrivastava On BEST ANSWER

Something like -

List<String> orderedSentenceList = new ArrayList<String>();
for (Map.Entry<String, String> entry : yourMap.entrySet()) {
    String key = entry.getKey();
    orderedSentenceList.add(originalSentenceList.get(key-1))
}

Use orderedSentenceList now

0
Daniel On

Is this what you are looking for?

import java.util.Map.Entry;

String[] array = new String[map.size()];
int i = 0;
for (Entry<Integer, String> entry : map.entrySet()) {
    array[i++] = entry.getValue();
}
0
Rey Libutan On

I hope I understand your question but here goes:

This is using String[] only as you requested.

String[] sentenceList = new String[yourLinkedHashMap.size()];
for (Map.Entry<Integer, String> entry : yourLinkedHashMap.entrySet()) {
   sentenceList[entry.getKey() - 1] = entry.getValue();
}
0
Sarfaraz Khan On

Something like this will help you develop your own solution

 String []sentences=new String[mp.size()] ;
 //mp is the map
    Iterator it = mp.entrySet().iterator();
    int i=0;
    while (it.hasNext()) {
         Map.Entry pair = (Map.Entry)it.next();
         sentences[i++]=pair.getValue();
    }