I've managed to solve this task with the code below, but it does't seem to be most efficient way to do this. What's the most compact way of solving this task? I would appreciate if somebody could post his/hers code with short explanation. Pointing out my mistakes and explaining them is also welcome.
package com.codegym.task.task07.task0712;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
/*
Shortest or longest
*/
public class Solution {
public static void main(String[] args) throws Exception {
ArrayList<String> list = new ArrayList<>();
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
//populating the list
for (int i = 0; i < 10; i++) {
String s = br.readLine();
list.add(s);
}
//creating two values for the next loops
int max = 0;
int min = Integer.MAX_VALUE;
//loops below loop through list and assign the length value of shortest and longest strings to ints above
for (int i = 0; i < list.size(); i++) {
if (list.get(i).length() > max) {
max = list.get(i).length();
}
}
for (int i = 0; i < list.size(); i++) {
if (list.get(i).length() < min) {
min = list.get(i).length();
}
}
// loop below compares the length of strings in list to max and min ints
// if the length of string matches min or max, the loop ends
for (int i = 0; i < list.size(); i++) {
if (list.get(i).length() == min) {
System.out.println(list.get(i));
break;
}
else if (list.get(i).length() == max){
System.out.println(list.get(i));
break;
}
}
}
}