Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple operations on java object using Stream and lambda

i have class A {int sNo; String name;} with valid constructor. i need to trim name and sort on the basis of name using stream API.

public class Test1 {
    public static void main(String[] args) {



    ArrayList<A> l = new ArrayList();
    l.add(new A(1, " 1name "));
    l.add(new A(7, " 3name "));
    l.add(new A(6, ""));
    l.add(new A(5, " 2name "));
    l.add(new A(4, " 5name "));
    l.add(new A(2, ""));

    List<String> i = l.stream()
            .filter(s -> !s.name.isEmpty())
            .map(s -> s.name.trim())
            .sorted()
            .collect(Collectors.toList());
    System.out.println(i); 
}

}

it is returning only name in sorted order

[, 1name, 2name, 3name, 5name]

but i need entire object.

i know s -> s.name.trim() is the reason its storing name only,

how can apply operation on particular filed but store entire object.

like image 551
shrikant.sharma Avatar asked Feb 28 '26 15:02

shrikant.sharma


1 Answers

Just for fun, not because it's particularly nice or even recommended. One could accomplish that also with anonymous Objects:

    List<A> i = l.stream()
            .filter(s -> !s.name.isEmpty())
            .map(s -> new Object() {A a = s; String name = s.name.trim();})
            .sorted(Comparator.comparing(o -> o.name))
            .map(o -> o.a)
            .collect(Collectors.toList());

Not every compiler will be happy about this (javac will), but it's valid Java code.

like image 88
apophis Avatar answered Mar 02 '26 05:03

apophis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!