For any given file, Write a Java program to find a line with maximum number of words in it is a very common interview question. In other words, write a Java program to find longest line from file
.
In this tutorial we will go over all detailed steps to programatically figure out longest line.
Here is complete logic:
- Read provided file using Java8
Stream.forEach()
loop. - Each line will be pass to
analyseLines()
method in which we will find total word count and update two variable if it’s longest line by comparing previously added valuelineCount
represents a line with maximum word countcrunchifyMaxWords
holds a value of total words
- In below Java program we will read file
FindLongestLineFromFile.txt
located under Documents folder. Please update file and location as per your system setup. - print() and println() are the simple print Utilities.
- Once reading complete file – we are printing result.
If you are interested in more file reading, working with lines and total number words then try to explore below articles:
- Read File, Count total number of Characters, Words & Lines
- Find Maximum Occurrence of Words from Text File
- Count Number of XML Elements in Java
How do I split a string with any whitespace chars as delimiters?
- Simple way is to split a string in java using
\\s+
delimiter.
CrunchifyFindLineWithMaxWordCount.java
package crunchify.com.tutorial; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; import java.util.stream.Stream; /** * * @author Crunchify.com * Program: From provided file, find a line which has maximum number of words in it * Version: 1.0.3 * */ public class CrunchifyFindLineWithMaxWordCount { private int crunchifyMaxWords = 0; private List<String> lineCount = new ArrayList<String>(); public int getCurrentMaxCount() { return crunchifyMaxWords; } public void setCurrentMaxCount(int crunchifyMaxWords) { this.crunchifyMaxWords = crunchifyMaxWords; } public List<String> getLines() { return lineCount; } public void setLines(List<String> lineCount) { this.lineCount = lineCount; } public static void main(String a[]) { CrunchifyFindLineWithMaxWordCount object = new CrunchifyFindLineWithMaxWordCount(); object.readMaxLineCount("/Users/ashah/Documents/FindLongestLineFromFile.txt"); print("\n\nHere is a line with Maximum Word Count in it ====> "); List<String> lineCount = object.getLines(); for (String crunchifyLine : lineCount) { println(crunchifyLine); } println("Above line contains " + object.getCurrentMaxCount() + " words."); } public void readMaxLineCount(String crunchifyFile) { Stream<String> crunchifyStream = null; try { // Read all lines from a file as a Stream. Bytes from the file are decoded into characters using the UTF-8 charset crunchifyStream = Files.lines(Paths.get(crunchifyFile)); } catch (IOException exception) { exception.printStackTrace(); } print("============= Printing file FindLongestLineFromFile.txt =============\n"); crunchifyStream.forEach(line -> analyseLines(line)); } private void analyseLines(String crunchifyLine) { println(crunchifyLine); // Split a string with any whitespace chars int crunchifyCount = (crunchifyLine.split("\\s+")).length; if (crunchifyCount > crunchifyMaxWords) { lineCount.clear(); lineCount.add(crunchifyLine); crunchifyMaxWords = crunchifyCount; } else if (crunchifyCount == crunchifyMaxWords) { lineCount.add(crunchifyLine); } } private static void println(String crunchifyLine) { System.out.println(crunchifyLine); } private static void print(String string) { System.out.print(string); } }
Eclipse Console Result:
============= Printing file FindLongestLineFromFile.txt ============= Simplest Spring MVC Hello World Tutorial Refresh Div Content Without Reloading Page JavaScript & Validate Username, Phone Field & Top 10 Java Questions Step To Setup Apache Tomcat In Eclipse & Build RESTful Service Using JAX-RS & Jersey Print List Of All Loading Spring Beans Here is a line with Maximum Word Count in it ====> Step To Setup Apache Tomcat In Eclipse & Build RESTful Service Using JAX-RS & Jersey Above line contains 15 words.
I hope you find this tutorial useful and interesting. Let me know if you have any more questions.
The post In Java How to find a Line with Maximum Number of Words? Using Stream.forEach() Iterator appeared first on Crunchify.
0 Commentaires