Alex Man
Alex Man

Reputation: 4886

Truncate a dynamic value using Java8

In one of my application I used to get some reference number like as shown below

BRD.2323-6984-4532-4444..0
BRD.2323-6984-4532-4445..1
BRD.2323-6984-4532-4446
BRD.2323-6984-4532-4446..5
:
:

How do I truncate the ending ..[n] if it contains in Java like as shown below. If it is a constant number I would have substring it like .substring(0, value.indexOf("..0")), since the number is dynamic should I use Regex?

BRD.2323-6984-4532-4444
BRD.2323-6984-4532-4445
BRD.2323-6984-4532-4446
BRD.2323-6984-4532-4446
:
:

Can someone please help me on this

Upvotes: 0

Views: 80

Answers (2)

WJS
WJS

Reputation: 40034

I noticed that one of them, when modified, would result in a duplicate. Here is something that might prove useful using @TimBiegeleisen's answer. It will eliminate duplicates.

List<String> values = List.of(
        "BRD.2323-6984-4532-4444..0",
        "BRD.2323-6984-4532-4445..1",
        "BRD.2323-6984-4532-4446",
        "BRD.2323-6984-4532-4446..5");
UnaryOperator<String> modify = str->str.replaceAll("\\.\\.\\d+$", "");
Set<String> set = values.stream()
        .map(modify::apply)
        .collect(Collectors.toSet());

set.forEach(System.out::println);

Prints

BRD.2323-6984-4532-4444
BRD.2323-6984-4532-4445
BRD.2323-6984-4532-4446

Upvotes: 0

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521063

You could use a regex replacement here:

String input = "BRD.2323-6984-4532-4444..0";
String output = input.replaceAll("\\.\\.\\d+$", "");
System.out.println(input);   // BRD.2323-6984-4532-4444..0
System.out.println(output);  // BRD.2323-6984-4532-4444

Note that the above replacement won't alter any reference number not having the two trailing dots and digit.

Upvotes: 1

Related Questions