使用Java 8 Stream解析日志文件,求完善代码实现
Solution to Parse Log Entries with Java 8 Streams
Let's break down how to fix your code to achieve the desired output. First, let's clarify the steps needed for each log entry:
- Extract the 3-letter racer code (e.g.,
SVF) as the key. - Split the remaining part of the entry into date and time using the underscore (
_) as the separator. - Wrap the date and time into an
ArrayList<String>. - Create a single-entry
HashMapfor each racer, then collect all these maps into aList.
Corrected Code
import java.io.IOException; import java.net.URISyntaxException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Arrays; import java.util.stream.Collectors; import java.util.stream.Stream; public class FileParser { private Stream<String> outputStream; // Adjusted the FileReader constructor call (assuming your custom class takes fileName as input) public FileParser(String fileName) throws IOException, URISyntaxException { FileReader fr = new FileReader(fileName); this.outputStream = fr.getStreamFromFile(fileName); } public List<HashMap<String, ArrayList<String>>> getRacersInfo() { return outputStream // Split single-line log content into individual entries (remove if entries are already on separate lines) .flatMap(line -> Arrays.stream(line.split("\\s+"))) // Process each entry into a single-entry HashMap .map(entry -> { String racerCode = entry.substring(0, 3); String[] dateTimeParts = entry.substring(3).split("_"); ArrayList<String> dateTimeList = new ArrayList<>(Arrays.asList(dateTimeParts)); HashMap<String, ArrayList<String>> racerMap = new HashMap<>(); racerMap.put(racerCode, dateTimeList); return racerMap; }) // Collect all maps into the final List .collect(Collectors.toList()); } }
Key Details:
- Entry Splitting: The
flatMapstep handles cases where the entire log is stored as a single line with entries separated by spaces. If each entry is already on its own line in the file, you can remove this line and process each line directly withmap. - Custom FileReader: I adjusted the
FileReaderconstructor to pass thefileNamesince empty file reader constructors are uncommon—tweak this if your custom class uses a different initialization pattern. - Flexibility Note: While you specified
ArrayList<String>in the return type, usingList<String>(instead of the concreteArrayList) is generally better for code flexibility. If possible, updating the return type toList<HashMap<String, List<String>>>would be a cleaner approach. - Error Handling: This code assumes all log entries are well-formed. To handle invalid entries (e.g., missing underscore, short code), add a
filteror try-catch block inside themapoperation to skip or log bad entries.
Example Output:
For your sample entry SVF2018-05-24_12:02:58.917, the resulting map will be:
{SVF = [2018-05-24, 12:02:58.917]}
The full list will contain one such map for every log entry as you requested.
内容的提问来源于stack exchange,提问作者IceTeaGreen
相关产品推荐
相关产品推荐

