Java 8 什么';在Java8中,用索引更新列表中的项目是一种更实用的方法吗?
鉴于:Java 8 什么';在Java8中,用索引更新列表中的项目是一种更实用的方法吗?,java-8,functional-programming,Java 8,Functional Programming,鉴于: 静态类项{ 字符串名; 整数指数; 项目(字符串名称){ this.name=名称; } } @试验 公开无效测试(){ 清单项目= stream(新字符串[]{“z”、“y”、“x”}) .map(项目::新建) .collect(Collectors.toList()); 排序(Comparator.comparing(o->o.name)); //开始功能化我 int i=0; 对于项目(it:项目){ it.index=i++; } //结束功能化我 assertEquals(0
静态类项{
字符串名;
整数指数;
项目(字符串名称){
this.name=名称;
}
}
@试验
公开无效测试(){
清单项目=
stream(新字符串[]{“z”、“y”、“x”})
.map(项目::新建)
.collect(Collectors.toList());
排序(Comparator.comparing(o->o.name));
//开始功能化我
int i=0;
对于项目(it:项目){
it.index=i++;
}
//结束功能化我
assertEquals(0,items.get(0.index));
assertEquals(1,items.get(1.index));
assertEquals(2,items.get(2.index));
}
在Java8中,在“functionalizeme”注释之间编写代码的更实用的方法是什么?我正在考虑使用reduce或collect的策略,但在我的脑海中看不到解决方案。您不应该假设收集器返回的列表是可变的。因此,您不能对其调用
sort
。在您的特定情况下,您可以在收集之前进行排序:
static class Item {
String name;
int index;
Item(String name) {
this.name = name;
}
}
@Test
public void test() {
List<Item> items =
Arrays.stream(new String[] {"z", "y", "x"})
.map(Item::new)
.collect(Collectors.toList());
items.sort(Comparator.comparing(o -> o.name));
// begin functionalize me
int i = 0;
for (Item it : items) {
it.index = i++;
}
// end functionalize me
assertEquals(0, items.get(0).index);
assertEquals(1, items.get(1).index);
assertEquals(2, items.get(2).index);
}
然后,可以使用更新列表项
List<Item> items = Stream.of("z", "y", "x")
.sorted()
.map(Item::new)
.collect(Collectors.toList());
您不应该假定收集器.toList()返回的列表是可变的。因此,您不能对其调用
sort
。在您的特定情况下,您可以在收集之前进行排序:
static class Item {
String name;
int index;
Item(String name) {
this.name = name;
}
}
@Test
public void test() {
List<Item> items =
Arrays.stream(new String[] {"z", "y", "x"})
.map(Item::new)
.collect(Collectors.toList());
items.sort(Comparator.comparing(o -> o.name));
// begin functionalize me
int i = 0;
for (Item it : items) {
it.index = i++;
}
// end functionalize me
assertEquals(0, items.get(0).index);
assertEquals(1, items.get(1).index);
assertEquals(2, items.get(2).index);
}
然后,可以使用更新列表项
List<Item> items = Stream.of("z", "y", "x")
.sorted()
.map(Item::new)
.collect(Collectors.toList());
可能的重复可能的重复