Java 将for循环转换为forEach Lambda
我正在学习Lambdas,在转换方面有点困难。我需要引入一个列表,使用类数组的asList方法将Field类的values方法提供的数组复制到该列表中。然后,我需要使用一个lambda表达式作为其参数,用forEach内部循环转换for循环。lambda表达式的主体将是for循环的当前主体代码。我相信我的列表语法是正确的(List List=Arrays.asList(data);),但我很难弄清楚如何处理for循环,甚至从何处开始。任何指导都将不胜感激。谢谢Java 将for循环转换为forEach Lambda,java,arrays,lambda,java-8,Java,Arrays,Lambda,Java 8,我正在学习Lambdas,在转换方面有点困难。我需要引入一个列表,使用类数组的asList方法将Field类的values方法提供的数组复制到该列表中。然后,我需要使用一个lambda表达式作为其参数,用forEach内部循环转换for循环。lambda表达式的主体将是for循环的当前主体代码。我相信我的列表语法是正确的(List List=Arrays.asList(data);),但我很难弄清楚如何处理for循环,甚至从何处开始。任何指导都将不胜感激。谢谢 public AreaData(S
public AreaData(String... data)
{
List<String> list = Arrays.asList(data);
/* Assert to check that the data is of the expected number of items. */
assert data.length == Field.values().length : "Incorrect number of fields";
for( Field field : Field.values() )
{
int width;
String formatString;
if( field == NAME )
{
/* Get the name value and store it away. */
String value = data[field.position()];
strings.put(field, value);
/* Get the needed width of the field to hold the name. */
width = max(value.length(), field.getFieldHeading().length());
formatString = "s";
} else
{
/* If the value is of the wrong form, allow the NumberFormatException
to be thrown. */
Double value = Double.parseDouble(data[field.position()]);
/* Assertion to check value given is positive. */
assert value.compareTo(0.0) >= 0 :
"invalid " + field.name() + " value=" + value.toString();
/* Get the field value and store it away. */
doubles.put(field, value);
/* Get needed width of the field to hold the heading or value. */
width = max((int) log10(value) + MINIMUM,
field.getFieldHeading().length() + HEADING_SEPARATION);
formatString = ".2f";
}
/* Keep the widest value seen, and record the corresponding format. */
if( width > WIDTHS.get(field) )
{
WIDTHS.put(field, width);
FORMATS.put(field, "%" + width + formatString);
}
}
/* Optimization: to avoid doing this every time a comparison is made. */
this.nameCaseless = strings.get(NAME).toUpperCase().toLowerCase();
}
公共区域数据(字符串…数据)
{
List=Arrays.asList(数据);
/*断言以检查数据是否为预期的项数*/
assert data.length==Field.values().length:“字段数不正确”;
for(字段:Field.values())
{
整数宽度;
字符串格式化字符串;
如果(字段==名称)
{
/*获取名称值并将其存储起来*/
字符串值=数据[field.position()];
strings.put(字段、值);
/*获取保存名称所需的字段宽度*/
宽度=最大值(value.length(),field.getFieldHeading().length());
formatString=“s”;
}否则
{
/*如果值的形式错误,请允许NumberFormatException
被扔掉*/
Double value=Double.parseDouble(数据[field.position()]);
/*检查给定值的断言为正*/
断言值。比较到(0.0)>=0:
“无效”+字段.name()+“value=“+value.toString()”;
/*获取字段值并将其存储起来*/
double.put(字段、值);
/*获取保存标题或值所需的字段宽度*/
宽度=最大值((int)log10(值)+最小值,
field.getFieldHeading().length()+HEADING\u分隔符);
formatString=“.2f”;
}
/*保留看到的最宽值,并记录相应的格式*/
if(宽度>宽度获取(字段))
{
宽度。放置(字段,宽度);
格式.put(字段“%”+宽度+格式字符串);
}
}
/*优化:避免每次进行比较时都这样做*/
this.nameCaseless=strings.get(NAME).toUpperCase().toLowerCase();
}
Stream.of(Field.values()).forEach()
public AreaData (String... data) {
List<String> list = Arrays.asList(data);
/* Assert to check that the data is of the expected number of items. */
assert data.length == Field.values().length : "Incorrect number of fields";
int width;
String formatString;
Stream.of(Field.values()).forEach(
field -> {
if (field == NAME) {
/* Get the name value and store it away. */
String value = data[field.position()];
strings.put(field, value);
/* Get the needed width of the field to hold the name. */
width = max(value.length(), field.getFieldHeading().length());
formatString = "s";
} else {
/* If the value is of the wrong form, allow the NumberFormatException
to be thrown. */
Double value = Double.parseDouble(data[field.position()]);
/* Assertion to check value given is positive. */
assert value.compareTo(0.0) >= 0 :
"invalid " + field.name() + " value=" + value.toString();
/* Get the field value and store it away. */
doubles.put(field, value);
/* Get needed width of the field to hold the heading or value. */
width = max((int) log10(value) + MINIMUM,
field.getFieldHeading().length() + HEADING_SEPARATION);
formatString = ".2f";
}
/* Keep the widest value seen, and record the corresponding format. */
if (width > WIDTHS.get(field)) {
WIDTHS.put(field, width);
FORMATS.put(field, "%" + width + formatString);
}
});
/* Optimization: to avoid doing this every time a comparison is made. */
this.nameCaseless = strings.get(NAME).toUpperCase().toLowerCase();
}
公共区域数据(字符串…数据){
List=Arrays.asList(数据);
/*断言以检查数据是否为预期的项数*/
assert data.length==Field.values().length:“字段数不正确”;
整数宽度;
字符串格式化字符串;
Stream.of(Field.values()).forEach(
字段->{
如果(字段==名称){
/*获取名称值并将其存储起来*/
字符串值=数据[field.position()];
strings.put(字段、值);
/*获取保存名称所需的字段宽度*/
宽度=最大值(value.length(),field.getFieldHeading().length());
formatString=“s”;
}否则{
/*如果值的形式错误,请允许NumberFormatException
被扔掉*/
Double value=Double.parseDouble(数据[field.position()]);
/*检查给定值的断言为正*/
断言值。比较到(0.0)>=0:
“无效”+字段.name()+“value=“+value.toString()”;
/*获取字段值并将其存储起来*/
double.put(字段、值);
/*获取保存标题或值所需的字段宽度*/
宽度=最大值((int)log10(值)+最小值,
field.getFieldHeading().length()+HEADING\u分隔符);
formatString=“.2f”;
}
/*保留看到的最宽值,并记录相应的格式*/
if(宽度>宽度获取(字段)){
宽度。放置(字段,宽度);
格式.put(字段“%”+宽度+格式字符串);
}
});
/*优化:避免每次进行比较时都这样做*/
this.nameCaseless=strings.get(NAME).toUpperCase().toLowerCase();
}
你应该考虑下面的经验法则:
理想情况下,lambda表达式最多应包含3行代码,并且
案例超过5行
如果您特别希望将其转换为使用streams和lambdas,那么我觉得您也应该抓住机会根据这些工具的意图对其进行重构。这意味着使用过滤器、收集器等,而不仅仅是将所有代码转换为单个lambda
例如:
Arrays.stream(Field.values())
.peek(field -> field.storeValue(data))
.filter(field -> field.getWidth(data) > widths.get(field))
.forEach(field -> storeWidthAndFormat(data, widths, formats));
这假设您将与名称相关的逻辑封装在字段
enum中(这是我的建议)。据我所知,这里没有理由使用lambda。@我看不到对列表=数组中定义的列表
的任何引用代码>所以我怀疑这一行可以删除。经验法则从何而来?在我的书中,一个lambda表达式应该理想地适合一行合理的长度。@StuartMarks这就是我使用“最多”的原因。一行是终极版,但三行仍然非常可读,就像这里的CheckPersonEligibleForSelectiveService
示例:@StuartMarks很有趣,我只是喜欢其中一行