[英]How can I convert this to use a java stream?
I have this method that will return an integer array of all the values in a specific position of all the enum values. 我有这个方法将返回所有枚举值的特定位置中的所有值的整数数组。 I'm wondering how I can convert this to a stream to make it shorter and more efficient. 我想知道如何将其转换为流,以使其更短,更有效。
So that method returns an integer array containing 12, 16, 19, 15 but I'm wondering how I can shorten it with a stream. 所以该方法返回一个包含12,16,19,15的整数数组,但我想知道如何用流来缩短它。
Thanks! 谢谢!
ITEM_1(12),
ITEM_3(16),
ITEM_4(19),
ITEM_5(15);
private final int ITEM_ID;
ENUM_NAME(int item_id) {
this.ITEM_ID = item_id;
}
public int[] getIDs() {
final ENUM_NAME[] enum_name = ENUM_NAME.values();
final int[] item_ids = new int[enum_name.length];
for (int i = 0; i < enum_name.length; i++) {
item_ids[i] = enum_name[i].getItemID();
}
return item_ids;
}
You can shorten looping through values with something like this: 您可以使用以下内容缩短值的循环:
Arrays.stream(ENUM_NAME.values()).map(t -> t.ITEM_ID)
It will create Stream with ITEM_ID values (values will be of type Integer) 它将使用ITEM_ID值创建Stream(值的类型为Integer)
To return int array (int[]), like getIDs() method in your code, use: 要返回int数组(int []),如代码中的getIDs()方法,请使用:
Arrays.stream(ENUM_NAME.values()).mapToInt(t -> t.ITEM_ID).toArray()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.