assassinsweed1 assassinsweed1 - 1 month ago 7
Java Question

How would you check the last 2 digits of each element in an ArrayList, Java?

I have been given a problem where I have an

ArrayList
containing integers which are between
100-99999999
. The size of the
ArrayList
varies. My task is that I have to search through the
ArrayList
to find elements which have the same last two digits.

For example if the
ArrayList
contains the following:
[100, 7999, 1023, 5556723, 6011, 48823]
and I asked it to print all the elements which end with "
23
"... it should print "
1023, 5556723, 48823
".

What would be the best way to approach this problem? I'm assuming you'd have to use a loop to search each element, however, how would you make sure it only checks the last two digits?

Thank you.

EDIT: I guess you could also filter out any elements which don't satisfy the condition and then just print the remaining elements left in
ArrayList
? I'm not sure if this would be possible.

Answer

You could rely on the Stream API by converting your Integer into String and check that they end with a given suffix as next:

List<Integer> values = Arrays.asList(100, 7999, 1023, 5556723, 6011, 48823);
String suffix = Integer.toString(23);
values.stream()
    .filter(i -> Integer.toString(i).endsWith(suffix))
    .forEach(System.out::println);

Output:

1023
5556723
48823

Or If you are only interested in printing the result it could be also:

System.out.println(
    values.stream()
        .map(i -> Integer.toString(i))
        .filter(s -> s.endsWith(suffix))
        .collect(Collectors.joining(", "))
);

Output:

1023, 5556723, 48823

Another approach with a modulo 100 that must be equals to our suffix.

int value = 23;
System.out.println(
    values.stream()
        .filter(i -> i % 100 == value)
        .map(i -> Integer.toString(i))
        .collect(Collectors.joining(", "))
);

Output:

1023, 5556723, 48823

how can you store the filtered values for later use? Instead of printing it.

With a Collector well chosen, for example let's say that you want to get a List, the previous code would then be:

int value = 23;
List<Integer> result =
    values.stream()
        .filter(i -> i % 100 == value)
        .collect(Collectors.toList());
System.out.println(result);

Output:

[1023, 5556723, 48823]