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

前端 未结 4 449
春和景丽
春和景丽 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:39

    Here's a version that makes use of Java 8's Stream API:

    String sentence = "PROGRAMMING IS FUN";
    List words = Arrays.asList(sentence.split(" "));
    
    String shortestWord = words.stream().min(
                                         Comparator.comparing(
                                         word -> word.length()))
                                        .get();
    
    System.out.println(shortestWord);
    

    You can also sort more complex objects by any of their attribute: If you have a couple of Persons and you wanted to sort them by their lastName, shortest first, the code becomes:

    Person personWithShortestName = persons.stream().min(
                                                     Comparator.comparing(
                                                     person -> person.lastName.length()))
                                                    .get();
    

提交回复
热议问题