[PYTHON] Compare how to write processing for lists by language

What would happen if I kept touching java7 all the time and suddenly wrote this process in another language? I thought, so I'll think about it for a moment. That's why I thought about the processing of arrays, which is common in web applications.

Requirements

↓ Narrow the list of json or map to age> 25, then sort by age in ascending order

[
  {"age":25, "name": "adam"},
  {"age":60, "name": "adamo"},
  {"age":30, "name": "larry"}
]

Case 1: Python (2.7)

In python, higher-order functions are defined by built-in functions, so as you write, the nesting gradually becomes deeper. Because of that, it's hard to understand what kind of array processing is done for what even with such a source.


users= [
  {"name":"adam","age":25},
  {"name":"adamo","age":60},
  {"name":"larry","age":30}
]

sorted(
  filter(lambda a: a['age']>25,
    users
  ),
  key=lambda a:a['age']
)

Case 2: Python (2.7) Other Approach

Currying is performed using partial, and method chains are performed using reduce. It doesn't seem like it's going to come out with this alone, but it may be better if it's a guy who can postpone the evaluation by returning a method like xrange.

from functools import partial
def chain(*args):
   return reduce(lambda x,f:f(x), args)

filter25 = partial(filter, lambda a: a['age']>25)
sortbyage = partial(sorted, key=lambda a:a['age'])

users=[
  {"name":"adam","age":25},
  {"name":"adamo","age":60},
  {"name":"larry","age":30}
]
chain(
  users,
  filter25,
  sortbyage
)

Case 3: scala

simple.

val users: List[Map[Symbol,String]] = List(
  Map('age->"25", 'name->"adam"),
  Map('age->"60", 'name->"adamo"),
  Map('age->"30", 'name->"larry")
)
users.filter(n => n.get('age).get.toInt > 25)
.sortBy(_.get('age).get)

If you keep the map, it lacks safety. I think it's a good idea to replace it with an array of classes at the beginning or map it in the middle.

//Pattern to change from the beginning
val users: List[Person] = List(
  new Person(25, "adam"),
  new Person(60,"adamo"),
  new Person(30,"larry")
)
users.filter(n => n.age > 25)
.sortBy(_.age)
//Pattern to change on the way
val users: List[Map[Symbol,String]] = List(
  Map('age->"25", 'name->"adam"),
  Map('age->"60", 'name->"adamo"),
  Map('age->"30", 'name->"larry")
)
users.map(n => new Person(n('age).toInt, n('name)))
.filter(n => n.age > 25)
.sortBy(_.age)

Case 4: java7 with guava:

In fact, there was a person who wrote such a source. It's a little easier to understand if you have knowledge of guava ... I wrote it properly, so when I noticed it, I used the class. The request is different from that of python.

List<Map<String, String>> users = ImmutableList.of<Map<String, String>>(
        ImmutableMap.of("name", "adam", "age", "25"),
        ImmutableMap.of("name", "adamo", "age", "60"),
        ImmutableMap.of("name", "larry", "age", "30")
);
FluentIterable
.from(users)
.transform(new Function<Map<String, String>, Person>(){
    @Override
    public Person apply(Map<String,String> map){
        return new Person(map.get("name"), new Integer(map.get("age")));
    }
})
.filter(new Predicate<Person>(){
    @Override
    public boolean apply(Person person){
        return person.age > 25;
    }
})
.toSortedImmutableList(Ordering.natural().onResultOf(
    new Function<Person, Integer>(){
        @Override
        public Integer apply(Person person){
            return person.age;
        }
    })
);

Case 5: java8

It is undeniable that the sort part is a little old-fashioned. The definition of the first data is quite annoying. Which is the best way?

List users = Collections.unmodifiableList(Arrays.asList(
    new HashMap<String, String>(){{put("age","25");put("name","adam");};},
    new HashMap<String, String>(){{put("age","60");put("name","adamo");};},
    new HashMap<String, String>(){{put("age","30");put("name","larry");};}
    )
);
users.stream()
.filter(a -> new Integer(a.get("age")) > 25)
.sorted((o1, o2) -> new Integer(o1.get("age")).compareTo(new Integer(o2.get("age"))))
.collect(Collectors.toList());

When I stored this in an object on the way, it became quite straightforward.

List users= Collections.unmodifiableList(Arrays.asList(
    new HashMap<String, String>(){{put("age","25");put("name","adam");};},
    new HashMap<String, String>(){{put("age","60");put("name","adamo");};},
    new HashMap<String, String>(){{put("age","30");put("name","larry");};}
    )
)
users.stream()
.map(a -> new Person(new Integer(a.get("age")), a.get("name")))
.filter(a -> a.age > 25)
.sorted(comparing(Person::getAge))
.collect(Collectors.toList());

ending

What happened because I saw only such a narrow thing? It feels like that, but at least I thought it would be better to throw away java7 and upgrade to java8.

I haven't written it this time, but since it's java7, if I proceed normally with procedural programming, I feel like I can't say anything because the code with side effects is written like "I'll write here as well" even with this kind of array processing, so the stream of java8 It is very attractive to be able to create code conventions with API.

Recommended Posts

Compare how to write processing for lists by language
How to write a test for processing that uses BigQuery
How to write a ShellScript Bash for statement
[Introduction to Python] How to write repetitive statements using for statements
[Natural language processing / NLP] How to easily perform back translation by machine translation in Python
XPath Basics (2) -How to write XPath
How to fix multi-columns generated by Pandas groupby processing to single
[Python] Try to classify ramen shops by natural language processing
Stack processing speed comparison by language
How to write a Python class
[For non-programmers] How to walk Kaggle
How to compare lists and retrieve common elements in a list
How to write soberly in pandas
Natural language processing for busy people
Flask reuse How to write html
By language: Regular expressions for passwords
How to use computer language slowly 2
Loose articles for those who want to start natural language processing
100 language processing knock 2020 "for Google Colaboratory"
How to write Docker base image
Summarize how to preprocess text (natural language processing) with tf.data.Dataset api
How to write Django1.9 environment-independent wsgi.py
How to use computer language slowly
100 Language Processing Knock Chapter 1 by Python
Preparing to start natural language processing
Notes on how to write requirements.txt
How to separate pipeline processing code into files by spider in Scrapy
3. Natural language processing with Python 1-2. How to create a corpus: Aozora Bunko
How to compare time series data-Derivative DTW, DTW-
Qiita (1) How to write a code name
How to set optuna (how to write search space)
100 Language Processing Knock-89: Analogy by Additive Constitutiveness
How to create * .spec files for pyinstaller.
How to write Python document comments (Docstrings)
[Python] Organizing how to use for statements
Decide who to vote for by lottery
How to install Windows Subsystem For Linux
How to use Pylint for PyQt5 apps
How to use fingerprint authentication for KDE
How to write Ruby to_s in Python
Summary of how to write AWS Lambda
How to write pydoc and multi-line comments
Entry where Python beginners do their best to knock 100 language processing little by little
How to write urlfetch unittest on GAE / P
[python] How to display list elements side by side
I tried to program bubble sort by language
How to use lists, tuples, dictionaries, and sets
How to specify the launch browser for JupyterLab 3.0.0
An introduction to object-oriented programming for beginners by beginners
How to use MkDocs for the first time
How to convert m4a acquired by iTunes to wav
How to make Spigot plugin (for Java beginners)
Python inexperienced person tries to knock 100 language processing 14-16
How to achieve time wait processing with wxpython
How to multi-process exclusive control in C language
[Django] How to get data by specifying SQL.
How to install Python for pharmaceutical company researchers
How to write regular expression patterns in Linux
How to use data analysis tools for beginners
Answer to "Offline Real-time How to Write F01 Problem"
How to erase the characters output by Python