比较数组中的字符串元素

发布于 2025-02-12 06:57:45 字数 152 浏览 1 评论 0 原文

我正在尝试比较数组中的元素。例如,

labels = ["abc1","abc2","abc3","abc4"]

我想取下最高值的字符串。在这种情况下,其ABC4。我对编码很陌生,因此,如果有人可以帮助我完成逻辑,那就太好了。

I am trying to compare elements in Array. for example,

labels = ["abc1","abc2","abc3","abc4"]

I want to take the String with the highest values. In this case its abc4. I'm pretty new to coding so if anyone could help me with the logic, it would be great.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

携君以终年 2025-02-19 06:57:45

您正在寻找的是一种将每个字符串相互比较的方法。

Java具有一种内置方法,可以为 String 类执行此操作,称为 compareTo 方法。顾名思义,它将一个字符串与另一个字符串进行比较。

String a = "abc1";
String b = "abc2";
String c = "abc1";
System.out.println(a.compareTo(b)); // prints a negative number because `a` is smaller than `b`
System.out.println(b.compareTo(a)); // prints a positive number because `b` is bigger than `a`
System.out.println(c.compareTo(a)); // prints 0 because `a` and `b` have the same letters.

请参阅 compareTo 方法:

[返回]值0如果参数字符串等于此字符串;如果该字符串在词典上小于字符串参数,则小于0的值;如果该字符串在词典上大于字符串参数,则大于0的值。

您可以在示例中使用此内容的方式是:

String biggest = labels[0];
for(int i = 1; i < labels.length; i++){
  if(biggest.compareTo(labels[i]) < 0) biggest = labels[i];
}
System.out.println(biggest);

注意:有关此方法如何选择“较大”的更多详细信息,请参见Java Doc(上面链接)。如果您有自己的规则应该更大的规则,那么您可以制作自己的方法来定义这一点。

更新:
例如,请参阅Xtremebaumer的评论

“ abc20” .compareto(“ abc100”)= 1。表明ABC20大于ABC100,因此使CompareTo()不一定对任务有用

What you are looking for is a method that compares each string to each other.

Java has a built-in method way to do this for the String class, called the compareTo method. As it's name suggests, it compares one string to another.

String a = "abc1";
String b = "abc2";
String c = "abc1";
System.out.println(a.compareTo(b)); // prints a negative number because `a` is smaller than `b`
System.out.println(b.compareTo(a)); // prints a positive number because `b` is bigger than `a`
System.out.println(c.compareTo(a)); // prints 0 because `a` and `b` have the same letters.

See the official java doc for the compareTo method:

[Returns]the value 0 if the argument string is equal to this string; a value less than 0 if this string is lexicographically less than the string argument; and a value greater than 0 if this string is lexicographically greater than the string argument.

The way you could use this in your example would be:

String biggest = labels[0];
for(int i = 1; i < labels.length; i++){
  if(biggest.compareTo(labels[i]) < 0) biggest = labels[i];
}
System.out.println(biggest);

Note: For more details on how this method chooses which one is "bigger", see the java doc (linked above). If you have your own rules about which one should be bigger, then you can make your own method to define that.

UPDATE:
For example, see XtremeBaumer's comment

"abc20".compareTo("abc100") = 1. Indicating that abc20 is bigger than abc100, thus making compareTo() not necessarily useful for the task

裸钻 2025-02-19 06:57:45

您的问题需要改进,根据您所说的话,让我们从字符串中删除所有ABC,获取最大整数,然后返回或打印“ ABC”串联到最大数字

import java.util.Arrays;
import java.util.stream.IntStream;

public class Solution {

    public static void main(String[] args) throws Throwable {
        int numberOfElements = 100;
        String[] labels = new String[numberOfElements];

        Arrays.setAll(labels, element -> "abc" + element);

        int max = Arrays.stream(labels).mapToInt(element -> Integer.parseInt(element.substring(3))).max().getAsInt();

        System.out.println(String.join(" | ", labels));

        System.out.println();
        System.out.println();
        System.out.println("The max here is : ");
        System.out.println("abc" + max);
    }
}

在这里输出:

abc0  |  | abc1  |  | abc2  |  | abc3  |  | abc4   ...... || abc99
    
The max here is : 
    abc99

Your question need improvement, based on what you said, lets remove all the abc from the Strings ,get the max integer and then return or print "abc" concatenated to the max number :

import java.util.Arrays;
import java.util.stream.IntStream;

public class Solution {

    public static void main(String[] args) throws Throwable {
        int numberOfElements = 100;
        String[] labels = new String[numberOfElements];

        Arrays.setAll(labels, element -> "abc" + element);

        int max = Arrays.stream(labels).mapToInt(element -> Integer.parseInt(element.substring(3))).max().getAsInt();

        System.out.println(String.join(" | ", labels));

        System.out.println();
        System.out.println();
        System.out.println("The max here is : ");
        System.out.println("abc" + max);
    }
}

Output here :

abc0  |  | abc1  |  | abc2  |  | abc3  |  | abc4   ...... || abc99
    
The max here is : 
    abc99
就像说晚安 2025-02-19 06:57:45

尝试这样的事情:

    var strings = new ArrayList<String>();
    strings.add("abc1");
    strings.add("abc2");
    strings.add("abc3");
    strings.add("abc4");


    var integers = strings
            .stream()
            .map(string -> Integer.valueOf(string.replaceAll("[^0-9]+", "")))
            .collect(Collectors.toList());
    var max = Collections.max(integers);
    var indexMax = integers.indexOf(max);
    var maxString = strings.get(indexMax);
    System.out.println(maxString);

Try something like this:

    var strings = new ArrayList<String>();
    strings.add("abc1");
    strings.add("abc2");
    strings.add("abc3");
    strings.add("abc4");


    var integers = strings
            .stream()
            .map(string -> Integer.valueOf(string.replaceAll("[^0-9]+", "")))
            .collect(Collectors.toList());
    var max = Collections.max(integers);
    var indexMax = integers.indexOf(max);
    var maxString = strings.get(indexMax);
    System.out.println(maxString);
影子的影子 2025-02-19 06:57:45

更简单的方法: @mcieciel 已经发布了这一信息。

List<String> list = Arrays.asList("abc1", "abc22", "abc33", "abc19");
List<Integer> intList = list.stream()
                            .map(s -> Integer.parseInt(s.replaceAll("[^0-9]+", "")))
                            .collect(Collectors.toList());
int index = intList.indexOf(Collections.max(intList));
System.out.println(list.get(index));

另一种方法是创建 map ,该将在键值对中具有字符串及其相应的整数值。

这可能是过度杀伤。

String key = list.stream()
                .collect(Collectors.toMap( // creating map like this format : abc1->1 , abc22->22 ...
                        Function.identity(), // key of the map i.e the string value
                        s -> Integer.parseInt(s.replaceAll("[^0-9]+", "")), // integer value
                        (e1, e2) -> e1)) // if multiple same entry exists choose one
                .entrySet() // now we have map, we can iterate and find out the key which holds max value
                .stream()
                .max((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue())) // comparing values
                .get()
                .getKey();

System.out.println(key);

注意:如果您没有任何数字的字符串值,则两者都无法正常工作。

Simpler way : @mcieciel has already posted this one.

List<String> list = Arrays.asList("abc1", "abc22", "abc33", "abc19");
List<Integer> intList = list.stream()
                            .map(s -> Integer.parseInt(s.replaceAll("[^0-9]+", "")))
                            .collect(Collectors.toList());
int index = intList.indexOf(Collections.max(intList));
System.out.println(list.get(index));

Another way is creating a map which will have string and its corresponding integer value in key-value pairs.Then find the max value with its key from the map.

This might be an overkill .

String key = list.stream()
                .collect(Collectors.toMap( // creating map like this format : abc1->1 , abc22->22 ...
                        Function.identity(), // key of the map i.e the string value
                        s -> Integer.parseInt(s.replaceAll("[^0-9]+", "")), // integer value
                        (e1, e2) -> e1)) // if multiple same entry exists choose one
                .entrySet() // now we have map, we can iterate and find out the key which holds max value
                .stream()
                .max((e1, e2) -> Integer.compare(e1.getValue(), e2.getValue())) // comparing values
                .get()
                .getKey();

System.out.println(key);

Note : if you have string values without any digit,both will not work.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文