Java - 查找字符串数组的最小值和最大值

时间:2021-09-22 16:01:04

I'm new to programming in java. The below source code is found in a book, when i try to execute the program it is showing some incorrect data.

我是java的编程新手。下面的源代码可以在一本书中找到,当我尝试执行该程序时,它会显示一些不正确的数据。

public class Pair<T> {

    private T first;
    private T second;

    public Pair() {
        first = null;
        second = null;
    }

    public Pair(T first, T second) {
        this.first = first;
        this.second = second;
    }

    public T getFirst() {
        return first;
    }

    public T getSecond() {
        return second;
    }

    public void setFirst(T newValue) {
        first = newValue;
    }

    public void setSecond(T newValue) {
        second = newValue;
    }  
}

Logic to find the min and max value of the string array

用于查找字符串数组的最小值和最大值的逻辑

public class ArrayAlg {

    public static Pair<String> minmax(String[] arr) {
        if (arr == null || arr.length == 0)
            return null;

        String min = arr[0];
        String max = arr[0];

        for (int i = 1; i < arr.length; i++) {
            if (min.compareTo(arr[i]) > 0)
                min = arr[i];
            if (max.compareTo(arr[i]) < 0)
                max = arr[i];
        }
        return new Pair<String>(min, max);

    }
}

public static void main(String[] args) {

        String[] words = { "Mary", "had", "a", "little", "lamb" };
        Pair<String> obj = ArrayAlg.minmax(words);
        System.out.println("Minvalue " + obj.getFirst());
        System.out.println("Maxvalue " + obj.getSecond());

    }

If you execute the above program, it displays Minvalue = Mary and MaxValue = little. The value a in the String array is the Minimum Value but in this case it is showing Mary as the Min Value.
Can anyone tell me the better approach to find the Minimum and Maximum value in the String array?

如果执行上述程序,则显示Minvalue = Mary和MaxValue = little。 String数组中的值a是最小值,但在这种情况下,它将Mary显示为最小值。谁能告诉我在String数组中找到最小值和最大值的更好方法?

4 个解决方案

#1


3  

The output you got is the correct output, since the natural ordering of Strings is lexicographical order, in which upper case letters come before lower case letters. Hence Mary is the "smallest" String.

你得到的输出是正确的输出,因为字符串的自然顺序是字典顺序,其中大写字母在小写字母之前。因此玛丽是“最小的”字符串。

In order not to use the natural ordering, don't use String's compareTo method. Instead you can implement whatever logic you see fit to determine which String is smaller. One way of introducing alternative ordering is passing a Comparator<String> instance to your minmax method and using its compare method to compare the Strings.

为了不使用自然顺序,请不要使用String的compareTo方法。相反,您可以实现您认为合适的任何逻辑,以确定哪个String更小。引入替代排序的一种方法是将Comparator 实例传递给minmax方法,并使用其compare方法比较字符串。

#2


3  

I think, for you purposes it's better to use String method compareToIgnoreCase().

我认为,为了您的目的,最好使用String方法compareToIgnoreCase()。

But it depends on you understanding what does Minimum string and Maximum string is.

但这取决于你理解最小字符串和最大字符串是什么。

Also, there is preffered way to compare any objects - via Comparator.

此外,还有一种比较任何对象的优先方式 - 通过比较器。

public static Pair<String> minmax(String[] arr) {
    if (arr == null || arr.length == 0)
        return null;

    Arrays.sort(arr, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2); // to compare by lexicographical order
            //return o1.length() - o2.lenth(); // to compare by length
        }
    });

    return new Pair<String>(arr[0], arr[arr.length - 1]);
}

Here are some links to follow:

以下是一些链接:

#3


1  

You will need to use a Comparator for this. You can sort the words alphabetically, ignoring case, by using the String.CASE_INSENSITIVE_ORDER Comparator.

您需要使用比较器。您可以使用String.CASE_INSENSITIVE_ORDER比较器按字母顺序对单词进行排序,忽略大小写。

In Java 8 this can be achieved easily using Lambdas:

在Java 8中,这可以使用Lambdas轻松实现:

public final Pair<String> miniMax(final String[] words) {
    final String min = Arrays.stream(words).min(String.CASE_INSENSITIVE_ORDER).orElse(null);
    final String max = Arrays.stream(words).max(String.CASE_INSENSITIVE_ORDER).orElse(null);
    return new Pair<>(min, max);
}

Testing:

测试:

String[] words = { "Mary", "had", "a", "little", "lamb" };
System.out.println(miniMax(words));

Output:

输出:

a, Mary

#4


1  

compareTo() compares the strings lexicographically, meaning that uppercase letters come before lowercase letters, since that is the order in Unicode. Instead, do one of the following:

compareTo()按字典顺序比较字符串,这意味着大写字母在小写字母之前,因为这是Unicode中的顺序。相反,请执行以下操作之一:

  • Use compareToIgnoreCase()

    使用compareToIgnoreCase()

  • Use a case-insensitive Comparator, readily available from String.CASE_INSENSITIVE_ORDER

    使用不区分大小写的比较器,可从String.CASE_INSENSITIVE_ORDER中随时使用

  • Use a full language-specific Comparator, that will order special characters and international letters like you would see in a book index, available from Collator.getInstance()

    使用完整的语言特定的比较器,它将订购特殊字符和国际字母,就像您在书籍索引中看到的那样,可从Collat​​or.getInstance()获得

Alternatively, for a good Java 8 implementation, see answer by arizzle.

或者,对于一个好的Java 8实现,请参阅arizzle的回答。

So, your loop could be:

所以,你的循环可能是:

for (int i = 1; i < arr.length; i++) {
    if (min.compareToIgnoreCase(arr[i]) > 0)
        min = arr[i];
    if (max.compareToIgnoreCase(arr[i]) < 0)
        max = arr[i];
}

Or:

要么:

Comparator<String> comp = Collator.getInstance();
for (int i = 1; i < arr.length; i++) {
    if (comp.compare(min, arr[i]) > 0)
        min = arr[i];
    if (comp.compare(max, arr[i]) < 0)
        max = arr[i];
}

#1


3  

The output you got is the correct output, since the natural ordering of Strings is lexicographical order, in which upper case letters come before lower case letters. Hence Mary is the "smallest" String.

你得到的输出是正确的输出,因为字符串的自然顺序是字典顺序,其中大写字母在小写字母之前。因此玛丽是“最小的”字符串。

In order not to use the natural ordering, don't use String's compareTo method. Instead you can implement whatever logic you see fit to determine which String is smaller. One way of introducing alternative ordering is passing a Comparator<String> instance to your minmax method and using its compare method to compare the Strings.

为了不使用自然顺序,请不要使用String的compareTo方法。相反,您可以实现您认为合适的任何逻辑,以确定哪个String更小。引入替代排序的一种方法是将Comparator 实例传递给minmax方法,并使用其compare方法比较字符串。

#2


3  

I think, for you purposes it's better to use String method compareToIgnoreCase().

我认为,为了您的目的,最好使用String方法compareToIgnoreCase()。

But it depends on you understanding what does Minimum string and Maximum string is.

但这取决于你理解最小字符串和最大字符串是什么。

Also, there is preffered way to compare any objects - via Comparator.

此外,还有一种比较任何对象的优先方式 - 通过比较器。

public static Pair<String> minmax(String[] arr) {
    if (arr == null || arr.length == 0)
        return null;

    Arrays.sort(arr, new Comparator<String>() {
        @Override
        public int compare(String o1, String o2) {
            return o1.compareToIgnoreCase(o2); // to compare by lexicographical order
            //return o1.length() - o2.lenth(); // to compare by length
        }
    });

    return new Pair<String>(arr[0], arr[arr.length - 1]);
}

Here are some links to follow:

以下是一些链接:

#3


1  

You will need to use a Comparator for this. You can sort the words alphabetically, ignoring case, by using the String.CASE_INSENSITIVE_ORDER Comparator.

您需要使用比较器。您可以使用String.CASE_INSENSITIVE_ORDER比较器按字母顺序对单词进行排序,忽略大小写。

In Java 8 this can be achieved easily using Lambdas:

在Java 8中,这可以使用Lambdas轻松实现:

public final Pair<String> miniMax(final String[] words) {
    final String min = Arrays.stream(words).min(String.CASE_INSENSITIVE_ORDER).orElse(null);
    final String max = Arrays.stream(words).max(String.CASE_INSENSITIVE_ORDER).orElse(null);
    return new Pair<>(min, max);
}

Testing:

测试:

String[] words = { "Mary", "had", "a", "little", "lamb" };
System.out.println(miniMax(words));

Output:

输出:

a, Mary

#4


1  

compareTo() compares the strings lexicographically, meaning that uppercase letters come before lowercase letters, since that is the order in Unicode. Instead, do one of the following:

compareTo()按字典顺序比较字符串,这意味着大写字母在小写字母之前,因为这是Unicode中的顺序。相反,请执行以下操作之一:

  • Use compareToIgnoreCase()

    使用compareToIgnoreCase()

  • Use a case-insensitive Comparator, readily available from String.CASE_INSENSITIVE_ORDER

    使用不区分大小写的比较器,可从String.CASE_INSENSITIVE_ORDER中随时使用

  • Use a full language-specific Comparator, that will order special characters and international letters like you would see in a book index, available from Collator.getInstance()

    使用完整的语言特定的比较器,它将订购特殊字符和国际字母,就像您在书籍索引中看到的那样,可从Collat​​or.getInstance()获得

Alternatively, for a good Java 8 implementation, see answer by arizzle.

或者,对于一个好的Java 8实现,请参阅arizzle的回答。

So, your loop could be:

所以,你的循环可能是:

for (int i = 1; i < arr.length; i++) {
    if (min.compareToIgnoreCase(arr[i]) > 0)
        min = arr[i];
    if (max.compareToIgnoreCase(arr[i]) < 0)
        max = arr[i];
}

Or:

要么:

Comparator<String> comp = Collator.getInstance();
for (int i = 1; i < arr.length; i++) {
    if (comp.compare(min, arr[i]) > 0)
        min = arr[i];
    if (comp.compare(max, arr[i]) < 0)
        max = arr[i];
}