CSV 또는 Java의 다른 파일에서 중복 요소를 제거하는 방법은 무엇입니까?
게시 됨: 2021-05-28파일에서 중복 행을 찾는 것은 어려운 문제가 아닙니다. 하지만 인터뷰 질문에서 사람들은 때때로 그들이 사용해야 하는 방법에 대해 매우 혼란스러워합니다.
이 자습서에서는 CSV 파일 및 기타 파일에서 중복을 제거하는 방법에 대한 단계를 살펴봅니다.
시작하자:
1 단계.
파일 CrunchifyFindDuplicateCSV
.java 만들기
2 단계.
- 아래 코드를 파일에 넣습니다.
- BufferedReader를 사용하여 파일을 읽습니다.
- 하나씩 HashSet에 행을 추가합니다.
- HashSet 클래스는 해시 테이블(실제로는 HashMap 인스턴스)이 지원하는 Set 인터페이스를 구현합니다. 집합의 반복 순서를 보장하지 않습니다. 특히 주문이 시간이 지나도 일정하게 유지된다는 보장은 없습니다. 이 클래스는 null 요소를 허용합니다.
- add() 메소드를 사용하여 행이 Set에 이미 존재하는지 여부를 확인하십시오.
- 지정된 요소가 아직 없는 경우 이 세트에 추가합니다. 보다 형식적으로, 이 세트에 Objects.equals(e, e2)와 같은 요소 e2가 포함되어 있지 않으면 지정된 요소 e를 이 세트에 추가합니다. 이 집합에 이미 요소가 포함된 경우 호출은 집합을 변경하지 않고 그대로 두고
returns false
.
- 지정된 요소가 아직 없는 경우 이 세트에 추가합니다. 보다 형식적으로, 이 세트에 Objects.equals(e, e2)와 같은 요소 e2가 포함되어 있지 않으면 지정된 요소 e를 이 세트에 추가합니다. 이 집합에 이미 요소가 포함된 경우 호출은 집합을 변경하지 않고 그대로 두고
- 일단 건너뛰면 해당 줄을 건너뛴 줄로 인쇄합니다.
crunchify.csv 파일
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 |
name city number age kedar kapan 9843875 23 sedai ktm 97798433 23 ayush kalopul 9856324 12 dipal ratopul 9842567 34 malla setiopul 1258496 33 ayush kalopul 9856324 12 babin karki hariyopul 32589 11 raju dhading 58432 44 sedai ktm 97798433 23 Crunchify , LLC PayPal . com Google . com Twitter . com FaceBook . com Crunchify , LLC Google . com Visa . com MasterCard . com Citi . com California Austin California |
CrunchifyFindDuplicateCSV.java
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 |
package crunchify . com . tutorial ; import java . io . BufferedReader ; import java . io . FileNotFoundException ; import java . io . FileReader ; import java . io . IOException ; import java . util . HashSet ; /** * @author Crunchify.com * How to Remove Duplicate Elements from CSV file in Java? */ public class CrunchifyFindDuplicateCSV { public static void main ( String [ ] argv ) { String crunchifyCSVFile = "/Users/Shared/crunchify.csv" ; // Reads text from a character-input stream, buffering characters so as to provide for the // efficient reading of characters, arrays, and lines. BufferedReader crunchifyBufferReader = null ; String crunchifyLine = "" ; // This class implements the Set interface, backed by a hash table (actually a HashMap instance). // It makes no guarantees as to the iteration order of the set; in particular, it does not guarantee that the order will // remain constant over time. This class permits the null element. HashSet < String > crunchifyAllLines = new HashSet < > ( ) ; try { crunchifyBufferReader = new BufferedReader ( new FileReader ( crunchifyCSVFile ) ) ; while ( ( crunchifyLine = crunchifyBufferReader . readLine ( ) ) ! = null ) { if ( crunchifyAllLines . add ( crunchifyLine ) ) { crunchifyLog ( "Processed line: " + crunchifyLine ) ; } else if ( ! crunchifyIsNullOrEmpty ( crunchifyLine ) ) { crunchifyLog ( "--------------- Skipped line: " + crunchifyLine ) ; } } } catch ( FileNotFoundException e ) { e . printStackTrace ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } finally { if ( crunchifyBufferReader ! = null ) { try { crunchifyBufferReader . close ( ) ; } catch ( IOException e ) { e . printStackTrace ( ) ; } } } } // Check if String with spaces is Empty or Null public static boolean crunchifyIsNullOrEmpty ( String crunchifyString ) { if ( crunchifyString ! = null && !crunchifyString.trim().isEmpty()) return false; return true ; } // Simple method for system outs private static void crunchifyLog ( String s ) { System . out . println ( s ) ; } } // Linux command to remove duplicate lines from file: // $ sort -u /Users/Shared/crunchify.csv |

IntelliJ IDE에서 Java 프로그램을 실행해 봅시다.
결과는 다음과 같습니다.
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 |
Processed line : name city number age Processed line : kedar kapan 9843875 23 Processed line : sedai ktm 97798433 23 Processed line : ayush kalopul 9856324 12 Processed line : dipal ratopul 9842567 34 Processed line : malla setiopul 1258496 33 --------------- Skipped line : ayush kalopul 9856324 12 Processed line : babin karki hariyopul 32589 11 Processed line : raju dhading 58432 44 --------------- Skipped line : sedai ktm 97798433 23 Processed line : Processed line : Crunchify , LLC Processed line : PayPal . com Processed line : Google . com Processed line : Twitter . com Processed line : FaceBook . com --------------- Skipped line : Crunchify , LLC --------------- Skipped line : Google . com Processed line : Visa . com Processed line : MasterCard . com Processed line : Citi . com Processed line : California Processed line : Austin --------------- Skipped line : California Process finished with exit code 0 |
이 Java 프로그램이 CSV 또는 다른 파일에서 중복 행을 찾는 데 유용하기를 바랍니다.
Linux 명령을 사용하여 CSV에서 중복 행을 찾는 방법은 무엇입니까?
1 |
$ sort - u / Users / Shared / crunchify . csv |
결과: