Skip to content

Python like list comprehensions in Java

aburkov edited this page Jun 27, 2015 · 5 revisions

With xpresso you can write pythonic list comprehension expressions in Java.

Python:

foreign_trips_lower = [city.lower() for city in trips if city not in russian_cities]

xpresso:

list<String> foreignTripsLower = x.list(x.<String>yield().apply(x.lower).forEach(trips).unless(x.in(russianCities)));

Python:

cool_cities = dict([(city.upper(),true) for (city, score) in rank.items() if score > 5])

xpresso:

dict<Integer> coolCities = x.dict(x.yield("city","_").apply(x.upper).replace(true).where("city","score").in(rank.items()).when(x.lambdaP("city, score : score > 20")));

Python:

evals = [True if value == "good" else False for value in some_list]

xpresso:

list<Boolean> evals = x.list(x.<Boolean>yield().replace(true).when(x.lambdaP("x : x == '''good'''")).replaceOtherwise(false).forEach(someList));

You can use list comprehensions to extract properties from element objects:

class PlannedTrip {
    int year;
    String city;
    
    public PlannedTrip(int year, String city) {
        this.year = year;
        this.city = city;
    }
 
    public int getYear() { return year; }
    public String getCity() { return city; }
}

list<PlannedTrip> plans = x.list(new PlannedTrip(2015, "Moscow"), new PlannedTrip(2016, "Paris"));

list<tuple> plansData = x.list(x.yield("year", "city").where("year", "city").in(plans));

x.print(plansData);

Console: [(2015, Moscow), (2016, Paris)]

You can also filter the extracted values in the same expression:

list<tuple> plansData = x.list(x.yield("year", "city").where("year", "city").in(plans).when(x.lambdaP("year, city : year > 2015)));

x.print(plansData);

Console: [(2016, Paris)]