I am new to Java streams and I just want to sort the keys for my object.
So, I try something like this and it works
List<FooSelect> li= Arrays.stream(obj.getFoos().getFoo()) //Stream<Foo>
.map(Foo::getSelect) //Stream<FooSelect>
.sorted(Comparator.comparing(FooSelect::getFoosKey)) //Stream<FooSelect>
.collect(Collectors.toList());
This sorts it according to what I want.
But the result I get is in List<FooSelect>
object, though I want it in List<Foo>
.
How can I change the mapping after it is sorted?
I want to again change the response in
//Stream<Foo> after it is sorted.
I want something like
List<Foo> li = same result of code above;
Class : FooSelect
just has some String fields
string FooKey
string FooTKey
and getters and setters for that (one of them is getFoosKey by which I am sorting)
Class: Foo
private FooSelect select
private FooInsert insert
Foo(select, insert)
public FooSelect getSelect() {
return select; }
Same way setter.
Remove the map
. The map
changes the object in the stream. Update the sorted statement as
.sorted(Comparator.comparing(f -> f.getSelect().getFoosKey()))
You can use lambda expression in Comparator.comparing
instead of method reference
List<Foo> res = foos.stream()
.sorted(Comparator.comparing(fo->fo.getSelect().getFooKey()))
.collect(Collectors.toList());
For just sorting you don't even need stream
foos.sort(Comparator.comparing(fo->fo.getSelect().getFooKey()));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.