05 December 2010

Create a map from a List with the valid and invalid percentages

Valid since: op4j 1.1

Given a List, create a map with two keys: "VALID" with the strings valid as a percentage between 0 and 100 and "INVALID" with the not valid ones

Our List<String> list variable contains some strings that, in some cases, represent valid percentages:

List<String> list = new ArrayList<String>();

Some of the strings in the list, do not represent valid percentages 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", "0", "32", "1,2"}));
result.put("INVALID", Arrays.asList(new String[] {"-13", "5k7", "ten"}));

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 percentage or not, put it into the list of VALID or INVALID values.

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.

  • FnNumber.between(min, max): returns wether the input number is between min and max or not

Let's see it coded with op4j:

Map<String, List<String>> validInvalidPercentages = 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))
&& Op.on(input).exec(FnString.toInteger(DecimalPoint.IS_POINT))
.exec(FnNumber.between(0, 100)).get().booleanValue()

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

1 comment:

  1. Thank you realy like the all idea, my code will get better now