05 December 2010

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

Valid since: op4j 1.1

Description
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

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

List<String> list = new ArrayList<String>();
list.add("5");
list.add("3.4");
list.add("-13");
list.add("0");
list.add("5k7");
list.add("ten");
list.add("32");
list.add("1,2");

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"}));

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 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))
.get().booleanValue()
&& Op.on(input).exec(FnString.toInteger(DecimalPoint.IS_POINT))
.exec(FnNumber.between(0, 100)).get().booleanValue()
? "VALID" : "INVALID";
}
}).get();

Comments
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

    ReplyDelete