//此程序打印String
向量中的所有最短元素我希望这个程序能够打印向量中所有最短的字符串。输出应为hello,test,JAVA
。最后一个字没有删除。任何人都可以帮忙,因为条件很清楚,我想。如果它的长度相同,则应将其删除。
import java.util.Vector;
class printAllSmallInVectorOfString
{
public static void main(String[] args)
{
Vector<String> v=new Vector();
v.addElement("hello");
v.addElement("test");
v.addElement("phytons");
v.addElement("JAVA");
v.addElement("Program");
v.addElement("ultrons");
String largest=""; // define largest
for(int i=0 ; i < v.size() ; i++)
{
// checks if first element is longer
if( largest.length() < v.elementAt(i).length())
{
// largest stores the string
largest=v.elementAt(i);
}
// condition for elements of same length
else if(v.elementAt(i).length() == largest.length())
{
System.out.println("The largest element so far is " + largest + " at index " + v.indexOf(largest ));
System.out.println(v.elementAt(i) + " at index " + v.indexOf(v.elementAt(i)) + " is the same length as the largest element " + largest + "\n");
// removes second element which is equal with longest
v.removeElementAt(i);
}
}
// removes longest element
v.removeElementAt(v.indexOf(largest));
for(String z : v)
System.out.println(z);
}
}
答案 0 :(得分:1)
我会这样做:
public static void main(String[] args) throws Exception {
final Collection<String> strings = Arrays.asList(
"hello",
"test",
"phytons",
"JAVA",
"Program",
"ultrons"
);
final int min = strings.stream()
.mapToInt(String::length)
.min()
.getAsInt();
final Collection<String> shortest = strings.stream()
.filter(s -> s.length() == min)
.collect(toList());
shortest.forEach(System.out::println);
}
首先,请勿使用Vector
。
现在,获取String
中Collection
的最小长度。
然后将Collection
和filter
取为该长度的String
。
最后,循环并打印Collection
。
答案 1 :(得分:1)
这是一个没有任何Java 8功能的简单解决方案。
public static void main(String[] args) {
Vector<String> v = new Vector();
v.addElement("hello");
v.addElement("test");
v.addElement("phytons");
v.addElement("JAVA");
v.addElement("Program");
v.addElement("ultrons");
System.out.println(keepShortest(v));
}
public static List<String> keepShortest(List<String> strings) {
// Find length of shortest string
int shortest = Integer.MAX_VALUE;
for (String string : strings) {
if (string.length() < shortest) {
shortest = string.length();
}
}
// Populate new list with shortest strings
List<String> newList = new ArrayList<>();
for (String string : strings) {
if (string.length() == shortest) {
newList.add(string);
}
}
return newList;
}
正如我上面所说,你需要: