0

I am new to java programming, and i have been trying to learn Collections in java,while learning i read about Collection.min(),and read that it gives the minimum value for given object. I wrote a very simple program to understand it, but which does nothing much useful,but it just's add values to my given set(Tree Set) and i tried to get the minimum value from the given set. When i ran the program Collections.min(set) printed nothing but Collections.min(set) printed a value for a sample test case:

Sample input

5
Abidevo
ARchana
balu
Guru
Padma

Collections.min(set) printed nothing,but Collections.max(set) printed

balu 

I tried to figure out this thing but i couldn't figure out,that why Collections.min(set) didn't printed anything, then i tried printing System.out.println(Collections.min(set,String.CASE_INSENSITIVE_ORDER)); still it printed nothing but, System.out.println(Collections.max(set,String.CASE_INSENSITIVE_ORDER)); printed

Guru

how does this Collection.min() works when it comes to finding minimum in String,I mean does it compare ascii sum (or) length of strings?And why in this case it is printing nothing?

import java.io.*;
import java.util.*;
public class TestClass {
     public static void main(String[] args) { 
       Scanner sc=new Scanner(System.in);
       int n;
       n=sc.nextInt();
       String[] coins=new String[n];
       Set<String> set=new TreeSet<String>();
       for(int  i = 0 ; i < n ; i++) {
         coins[i]=sc.nextLine();
       }
       for (int i = 0; i < coins.length; i++) {
         set.add(coins[i]);
       }
       System.out.println(Collections.min(set));
    }
}
Ayush Mishra
  • 247
  • 1
  • 14
  • 5
    Print out everything in your set, you have an empty string inside it, this empty string is the first value matched when comparing the strings. See [Scanner is skipping nextLine() after using next() or nextFoo()?](https://stackoverflow.com/questions/13102045/scanner-is-skipping-nextline-after-using-next-or-nextfoo) – Ferrybig Mar 02 '19 at 11:56
  • @Ferrybig,yes its all because of the line n=sc.nextInt(); am i correct? – Ayush Mishra Mar 02 '19 at 11:59
  • 2
    Yes, when you do `sc.nextInt()`, it only reads the numbers, but leaves the line enter afterwards in the buffered, then the next call to `nextLine()` just sees a newline, so it assumes it received an empty line, follow the solutions at the linked question for work arounds around the problem https://stackoverflow.com/a/13102066/1542723 – Ferrybig Mar 02 '19 at 12:16

0 Answers0