Java: Finding the shortest word in a string and printing it out

前端 未结 4 451
春和景丽
春和景丽 2020-12-21 11:11

I\'m a novice with Java. I took a class in C, so I\'m trying to get myself out of that mode of thinking. The program I\'m writing has a section in which the user enters an i

4条回答
  •  悲&欢浪女
    2020-12-21 11:31

    Java 8 has made it simpler. Convert your String array to a list and use sorted() to compare and sort your list in ascending order. Finally, use findFirst() to get the first value of your list (which is shortest after sorting).

    have a look,

    String[] words = new String[]{"Hello", "name", "is", "Bob"};
    String shortest = Arrays.asList(words).stream()
          .sorted((e2, e1) -> e1.length() > e2.length() ? -1 : 1)
          .findFirst().get();
    
    System.out.println(shortest);
    

提交回复
热议问题