Follow @devglan
Java Program to Find line with max character length in Descending Order
Description
This java interview program is about finding lines with max character from a file in descending order.In this case, we will be using buffered reader to read a file and use java provided data structure TreeSet to hold the line and it's character length as it automatically maintains ascending order.Following is the program to find two lines with max characters in descending order.
MaxCharacterLine.javapackage com.devglan; import java.io.BufferedReader; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import java.util.Comparator; import java.util.Set; import java.util.TreeSet; public class MaxCharacterLine { public static void main(String[] args) { BufferedReader br; String filePath = args[0]; int topList; SetliSet = new TreeSet (new MyComp()); try { br = new BufferedReader(new FileReader(new File(filePath))); String line = br.readLine(); topList = Integer.parseInt(line.trim()); while((line = br.readLine()) != null){ line = line.trim(); if(!"".equals(line)){ liSet.add(new Entries(line.length(), line)); } } int count = 0; for(Entries ent:liSet){ System.out.println(ent.line); if(++count == topList){ break; } } } catch (FileNotFoundException e) { System.out.println(e.getMessage()); e.printStackTrace(); } catch (IOException e) { System.out.println(e.getMessage()); e.printStackTrace(); } } public static class Entries{ Integer length; String line; public Entries(Integer l,String line){ length = l; this.line = line; } } public static class MyComp implements Comparator { @Override public int compare(Entries e1, Entries e2) { if(e2.length > e1.length){ return 1; } else { return -1; } } } }
Explanation
Click to Suggest Your Own Explanation
Read a file using BufferedReader and use TreeSet to hold the key value pair in the Entry set.Since, Entries is a custom object, implement Comparator for sorting the Entries by length property.Since, TreeSet by implmenetation maintains ascending order, the comparison in compare method is reversed.
Other Similar Java Programs:
If You Appreciate This, You Can Consider:
- Share this article on social media or with your teammates.