2015-01-23 1 views
-1

.txt에서 String 배열을 만들고이 문자열을 키로 사용하여 HashMap을 만들고 싶습니다. 하지만 하나의 값에 하나의 키로 String을 사용하고 싶지는 않습니다. 각 정보를 HashMap의 새로운 키로 사용하고자합니다.해시 맵에서 키 배열로 문자열 배열을 사용하려면 어떻게해야합니까?

private static String[] readAndConvertInputFile() { 
String str = StdIn.readAll(); 
String conv = str.replaceAll("\'s", "").replaceAll("[;,?.:*/\\-_()\"\'\n]", " ").replaceAll(" {2,}", " ").toLowerCase(); 
return conv.split(" "); } 

문자열의 정보는 ("단어", "물건", "기타", "pp.", "물건"과 같습니다.

내 값은 텍스트의 단어 빈도 여야합니다. 그래서 예를 들어 키 : "단어"값 : 1, 키 : "물건"값 : 2 등등 ... 누군가가 나를 도와 줄 수 있다면, 나는 단서가있다. :) 단어가 등장하는 횟수를 추적하기 위해 키 각 array 인덱스의 String 값 및 값으로 Integer을 사용하는 동안

+0

당신이 (HTTPS [Multimap과]을 찾고 계십니까 스트림 사용 : //google-collections.googlecode에게. co.kr/svn/trunk/javadoc/co.kr/google/common/collect/Multimap.html)? – StackFlowed

+0

@StackFlowed 거기에 닫는 괄호를 던지기를 원할 수도 있습니다.) –

+0

@QPaysTaxes done! – StackFlowed

답변

2

당신은 Map을 만들 수 있습니다.

Map<String,Integer> map = new HashMap<String,Integer>(); 

이 증가 할 때 Map 이미 키를 포함하는 경우, 당신은 확인하실 수 있습니다, 그것은 않는 경우는 true, 그렇지 않은 경우는, 그래서 1

if (occurences.containsKey(word)) { 
    occurences.put(word, occurences.get(word) + 1); 
} else { 
    occurences.put(word, 1); 
} 

로 설정, 1을 증가 문자열 배열을 반복하면서 String을 소문자로 변환하고 (단어 발생에 대한 대소 문자를 무시하려는 경우) 위의 if 문을 사용하여지도를 증가시킵니다.

for (String word : words) { 
    word = word.toLowerCase(); // remove if you want case sensitivity 
    if (occurences.containsKey(word)) { 
     occurences.put(word, occurences.get(word) + 1); 
    } else { 
     occurences.put(word, 1); 
    } 
} 

전체 예제가 아래에 나와 있습니다. 나는 소문자로 변환하여 대소 문자를 무시하고 대문자를 유지하려면 소문자로 변환 한 행을 제거합니다.

Word "cat" appeared 2 times. 
Word "fish" appeared 1 times. 
Word "horse" appeared 1 times. 
Word "the" appeared 2 times. 
Word "dog" appeared 1 times. 
Word "this" appeared 2 times. 
Word "has" appeared 1 times. 
1

예, 당신이 배열을 사용할 수 있습니다 (관계없이 요소 유형의)를 HashMap 키와 : 나에게 출력을 줄 것이다

public static void main(String[] args) { 

    String s = "This this the has dog cat fish the cat horse"; 
    String[] words = s.split(" "); 
    Map<String, Integer> occurences = new HashMap<String, Integer>(); 

    for (String word : words) { 
     word = word.toLowerCase(); // remove if you want case sensitivity 
     if (occurences.containsKey(word)) { 
      occurences.put(word, occurences.get(word) + 1); 
     } else { 
      occurences.put(word, 1); 
     } 
    } 

    for(Entry<String,Integer> en : occurences.entrySet()){ 
     System.out.println("Word \"" + en.getKey() + "\" appeared " + en.getValue() + " times."); 
    } 

} 

.

아니요, 이 아닙니다. 그 행동은 (일반적으로) 당신이 원하는 것일 것 같지는 않습니다.

당신의 특별한 경우에는 왜 배열을 키로 사용하는지 제안하는 이유가 없습니다. 귀하의 배열 요소 중에서 키로 그려진 String을 원하는 것 같습니다.

당신은 그래서 같은 단어 빈도 테이블을 만들 수 :

Map<String, Integer> computeFrequencies(String[] words) { 
    Map<String, Integer> frequencies = new HashMap<String, Integer>(); 

    for (String word: words) { 
     Integer wordFrequency = frequencies.get(word); 

     frequencies.put(word, 
       (wordFrequency == null) ? 1 : (wordFrequency + 1)); 
    } 

    return frequencies; 
} 
+0

우리가 삼항 연산자를 사용함에 따라 매우 까다로워지기를 원한다면, 다음과 같이 할 수 있습니다 : frequency.put (word, (frequencies.containsKey (word))? frequencies.get (word) + 1 : 1); 'for 루프 내부. 물론 가독성을 없애줍니다. – Compass

+0

@Compass, 그렇습니다.하지만 각 단어의 두 번째 및 후속 출연 (두 개는 각각'containsKey()','get()'및' put()'). 일반적으로'containsKey()'는'get()'으로 후속 작업을하는 경우 낭비입니다. –

+0

사실, 키가 실제로 'null'에 매핑되는 것에 대해 걱정할 필요가 없다면 말입니다. –

0

자바 8에서

String[] array=new String[]{"a","b","c","a"}; 
Map<String,Integer> map1=Arrays.stream(array).collect(Collectors.toMap(x->x,x->1,(key,value)->value+1)); 
관련 문제