0

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.

4
  • @Aomine How can i do that ? I tried, but it gives me error only. Can you please just describe that line ? Commented Oct 3, 2019 at 16:08
  • show how Foo and FooSelect look like i.e. their definitions then it would make it easier for people to answer your post Commented Oct 3, 2019 at 16:09
  • List<Foo> li = same result of code above; => List<FooSelect>, can you show us, how is that possible? Commented Oct 3, 2019 at 16:13
  • @Aomine Updated the code Commented Oct 3, 2019 at 16:16

2 Answers 2

1

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()));
Sign up to request clarification or add additional context in comments.

Comments

1

Remove the map. The map changes the object in the stream. Update the sorted statement as

.sorted(Comparator.comparing(f -> f.getSelect().getFoosKey()))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.