Iterate through large array, find and replace the element in a string efficiently in JAVA

I have a scenario where in I need to iterate through an array say

String[] numbers = {"1","2","3",......"10000"}

Now, I need to iterate through each array elements to check the number is present in a given string or not.

If the number is present, I need to replace it as 1a,2a,3a etc...

At present I am using for loop for iteration, If for conditioning and replaceAll function to replace all occurrences in that string. but, the performance is very bad. Is there any efficient way to do this?

Thanks in advance.

2 answers

  • answered 2020-10-20 13:56 Nikolas Charalambidis

    You can use Arrays.asList(T... a) which returns a fixed-size list backed by the specified array, therefore all the further operations affect the array. There is a method List::replaceAll(UnaryOperator<E>) available where you can use a lambda expression mapping the value to a new one (add 'a' suffix) if is parseable into an Integer. Minimal sample:

    String[] numbers = {"1","2","3","x", "10000"};
    Arrays.asList(numbers)
          .replaceAll(str -> {
              try {
                  Integer.parseInt(str);              // try if can be parsed into a number
                  return String.format("%sa", str);   // if so, add 'a', '%s' is replaced
              } catch (NumberFormatException nfe) {   // if not, leave it as is
                  return str;
              }
          });
    
    System.out.println(Arrays.toString(numbers));    // [1a, 2a, 3a, x, 10000a]
    

    If for conditioning and replaceAll function to replace all occurrences in that string. but, the performance is very bad.

    Even for 100'000 items in the numbers array, the method is anything but slow. Don't you mean String::replaceAll(String, String) instead which uses Regex - then the statement becomes true.

    In case of decimal numbers, you might want to use Double.parseDouble(String) instead. Also beware of the issue with different decimal sparators (. vs ,).

  • answered 2020-10-20 14:02 Israel Kouperman

    Stream API with parallel will result as the fastest for large arrays.

    String myNumber = "1";
    final String[] stringList = new String[0];
    final List<String> listStrings = Stream.of(stringList)
        .parallel()
        .map((s) -> s.replace(myNumber, myNumber + "a"))
        .collect(Collectors.toList());
    

    Java Stream API: https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html