05 December 2010

Create a map from a List and generate a List with the strings convertible to Integer

Valid since: op4j 1.1

Description
For a given List<String>, create a Map with two keys: "VALID" with the strings valid as integer and "INVALID" with the not valid ones. Convert the valid strings to integer.

Scenario
Our List<String> list variable contains some strings that, in some cases, represent integer numbers:

List<String> list = new ArrayList<String>();
list.add("5");
list.add("3.4");
list.add("89.7");
list.add("-13.999");
list.add("5f7");
list.add("537");
list.add("323a");
list.add("3,23");

Some of the strings in the list, do not represent valid integers and we want to create a map with two keys: INVALID whose value will be a list with the invalid strings and VALID which will have a list with the valid ones as its value:

Map<String, List<String>> result = new LinkedHashMap<String, List<String>>();
result.put("VALID", Arrays.asList(new String[] {"5", "3.4", "89.7", "-13.999", "537", "3,23"}));
result.put("INVALID", Arrays.asList(new String[] {"5f7", "323a"}));

The items in the VALID list, will be converted into integer...and that List<Integer> will be the output we want.

Recipe
Steps:
1. Create a map from the input list with two keys: VALID and INVALID. Depending on whether a string in the input list represents a valid integer or not, put it into the list of VALID or INVALID values.
2. Iterate the list of valid strings and convert them into integer numbers.

op4j funcions involved:
  • FnString.isInteger(decimalPoint): returns whether the input is valid as an integer or not based on the given decimal point. It does not check the string represents a non decimal number that fits in an Integer number but that FnString.toInteger can be executed correctly.

  • FnString.toInteger(decimalPoint): converts the input value into an integer based on the given decimal point.

Let's see it coded with op4j:

Map<String, List<String>> validInvalidIntegers = Op.on(list).zipAndGroupKeysBy(
new IFunction<String, String>() {
public String execute(String input, ExecCtx ctx) throws Exception {
return Op.on(input).exec(FnString.isInteger(DecimalPoint.IS_POINT))
.get().booleanValue()? "VALID" : "INVALID";
}
}).get();

List<Integer> asIntegerIfPoint = Op.on(result.get("VALID")).forEach()
.exec(FnString.toInteger(DecimalPoint.IS_POINT)).get();

Comments
We are supposing the valid decimal point is POINT though, if it were COMMA, it would be the same but using DecimalPoint.IS_COMMA instead

No comments:

Post a Comment