2

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
gayat
  • 43
  • 4
  • 3
    How would you do that? In your own words, not in code. Once you figure that out, is there a way to translate that to code? – Federico klez Culloca Jun 30 '22 at 10:33
  • what means "highest values" ? – Oussama ZAGHDOUD Jun 30 '22 at 10:34
  • Perhaps this one could be helpful: https://stackoverflow.com/questions/1217228/what-is-the-java-equivalent-for-linq – Stefan Wuebbe Jun 30 '22 at 10:35
  • @FedericoklezCulloca I am thinking of using CharAt() to compare. but im not exactly sure of the logic – gayat Jun 30 '22 at 10:35
  • 1
    @OussamaZAGHDOUD the one with the highest value at the end. abc4 is the highest here because its got 4 – gayat Jun 30 '22 at 10:37
  • First of all please describe how *you* determine which value is "highest". Try to specify some general steps needed to determine that (in other words describe *logic* you are following, because that logic is also something which your code will need to follow). Use [edit] option to clarify your question. – Pshemo Jun 30 '22 at 10:43
  • 1
    Also describe properties of values you want to work on. Does it always start with `abc`? If data always have 3 letters and then number? Is number always in range `0-9` or can it have more digits? Can there be more numbers in value mixed with letters like `abc12efg34` (if yes how would you like to handle it)? Etc.. – Pshemo Jun 30 '22 at 10:46

4 Answers4

3

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

Moish
  • 452
  • 1
  • 3
  • 13
  • 2
    `"abc20".compareTo("abc100")` = 1. Indicating that `abc20` is bigger than `abc100`, thus making `compareTo()` not necessarily useful for the task – XtremeBaumer Jun 30 '22 at 11:07
  • That was what I was addressing in my note, but I'll add your example. – Moish Jun 30 '22 at 11:21
2

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
Oussama ZAGHDOUD
  • 1,767
  • 5
  • 15
2

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);
mcieciel
  • 59
  • 3
2

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.

Sayan Bhattacharya
  • 1,365
  • 1
  • 4
  • 14