【发布时间】:2025-05-04 22:10:01
【问题描述】:
我正在学习 Lambda,但在转换时遇到了一点困难。我需要引入一个 List,使用类 Arrays 的 asList 方法将 Field 类的 values 方法提供的数组复制到其中。然后我需要使用 lambda 表达式作为参数将 for 循环转换为 forEach 内部循环。 lambda 表达式的主体将是当前 for 循环主体的代码。我相信我的 List 语法是正确的( List list = Arrays.asList(data); ),但我很难弄清楚如何处理 for 循环,甚至从哪里开始。任何指导将不胜感激。谢谢
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();
}
【问题讨论】:
-
据我所知,这里没有理由使用 lambda。