Read file and count same entries in Java
I need some advice. I know how to solve this problem clumsily, but I want to do it the right way, as I need to impress someone for a potential internship.
I have a textfile, for example:
[XXX开发者_如何学运维622] [YYY] [LLL] [E77700] [NNN] [6JL99NNN] [HH66] [0770LLL] [R88] [VVV]
[B177HQ] [8RR22] [PPP] [GGG] [CCXXXGG] [8IIXX0] [3KCC] [00222]
[222] [OO] [OO] [OO] [99] [555444] [33]
I need to read the entries and then do processes with them, for example sort alphabetically.
The process I don't know how to do is counting how many similar entries are in each line.
If I read the entries into a string array and pass the array to the counting method, then how should I make it so the method knows from which line each entry is? Should I create a 2D array and insert the linenumber along with the entry into it as a string?
Thanks in advance!
Here's a hint.
Use a Map
(some concrete implementation thereof; HashMap
would work) when you process the line. If you know how to insert an entry into a Map
, and if you know how to tell if an entry already exists in the Map
, you have your solution!
If you really want to impress them explain to them why the Map
solution is fast and then also explain the speed vs. memory trade-offs. Using Big-O notation will impress them more and will also show that you know what you're talking about.
I'm not going to give you the entire (working) solution since you said this was for an internship. If your intent is to impress them, you should work out the solution yourself. Presenting a community solution as your own would be a little dishonest, in my opinion.
You have a few good options. The simplest would be to simply read the entries in and process them one line at a time, rather than all at once. Another option would be to create a class that represents a line:
public class CodeLine {
public int lineNumber;
public List<string> codes;
}
This is a more "object-oriented" way to represent your lines, as opposed to a 2D array.
精彩评论