본문 바로가기
프로그래밍/Java

[JAVA 코드] HashMap value값에 따라 그룹화

by purplebulb 2019. 2. 28.
반응형


1. [파일]  : file_sample.txt

영수, 70

수영, 80

은지, 80

철수, 90

가영, 60



2. [자바 코드]

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map.Entry;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
 
    
public class convert {
 
    public static void main(String[] args) throws IOException {
        
        convert convert = new convert();
        convert.getFile();
        convert.grouping();
 
    }
 
    
    
        // 전역 변수 선언
        Map<String,String> Word = new HashMap<String,String>();
     
        // 파일 읽기
        public Map<StringString> getFile() throws FileNotFoundException {
     
        File file = new File("C:/Users/kej82/Desktop/sample.txt");
     
        try {
                System.out.println(file.getAbsoluteFile() + " reading...");
                BufferedReader inFiles = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), "UTF8"));
                
                String line = "";
                while((line = inFiles.readLine()) != null) {
                 if(line.trim().length() > 0) {
                     String [] line2 = line.split(",");
                     Word.put(line2[0],line2[1]);
                 }
                }
                
                inFiles.close();
                
               } catch (Exception e) {
                e.printStackTrace();
               }
     
     
           return Word;
        }
     
     
        public void grouping() throws FileNotFoundException {
        // 그룹화_ mapbyValueGrouping
        Map<String, List<String>> wordTypeList = Word.keySet().stream()
                                            .collect(Collectors.groupingBy(Word::get, TreeMap::new, Collectors.toList()));
        
        System.out.println(wordTypeList);
     
        }
        




3. 결과






댓글