假设我有以下类(class):
public class Foo {
private int id;
private String name;
public int getId() {
return id;
}
public Foo setId(int id) {
this.id = id;
return this;
}
public String getName() {
return name;
}
public Foo setName(String name) {
this.name = name;
return this;
}
}
然后,我有几个Foo
Collection<Foo> fooCollection
中的对象和字符串数组 String[] names
.
现在我要订购fooCollection
由属性(property)name
,以相同的顺序name
字符串在 names
中排序.
我如何使用 Java 8 Stream 做到这一点?
最佳答案
您可以使用 Arrays.asList(names).indexOf(f.getName())
作为比较键:
List<String> nameList = Arrays.asList(names);
List<Foo> fooList = new ArrayList<>(fooCollection);
fooList.sort(Comparator.comparingInt(f -> nameList.indexOf(f.getName())));
或者如果您确实需要 Stream API:
List<Foo> fooList = fooCollection.stream()
.sorted(Comparator.comparingInt(f -> nameList.indexOf(f.getName())))
.collect(Collectors.toList());
但是如果你有很多名字,你可以考虑提高效率,首先准备一个名字的反向索引:
Map<String, Integer> nameMap = IntStream.range(0, names.length)
.boxed()
.collect(Collectors.toMap(idx -> names[idx], Function.identity()));
List<Foo> fooList = fooCollection.stream()
.sorted(Comparator.comparing(f -> nameMap.get(f.getName())))
.collect(Collectors.toList());
这里我假设所有的名称都是不同的,并且每个 Foo
在 names
数组中都有相应的名称。
关于sorting - Java 8 - 通过具有在数组中定义的顺序的属性对对象集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41343619/