I was addicted to using Java's Stream API in Scala

Introduction

Overview

I'm new to Scala, and I'm addicted to mixing Java and Scala Lists. I think that people who usually write Java and are new to Scala may be addicted to it, so I will share the cause and solution.

environment

Thing you want to do

I want to extract only the necessary information from the list of tweets returned by the API of Twitter4J (ResponseList [Status]) and get a List of my own class Tweet type. In Java, if you use Stream API, you can kill it instantly.

Original code

code

The ResponseList returned from the Twitter4J API can use the Stream API, so it looks like this when written in Java style.

val statuses: ResponseList[Status] = twitter.getUserTimeline(paging)
      val tweets: List[Tweet] = statuses
        .stream()
        .map(status => new Tweet(status.getId, status.getText, status.getUser.getName))
        .collect(Collectors.toList) //For some reason there is a compile error here ...

Cause

The Stream API termination operation .collect (Collectors.toList) returns java.util.List, but the type of the variable to be stored is Scala List type.

Scala can use both Scala API and Java API, but they are different. Both offer types with the same name, but don't mix them up.

Policy to rewrite

1. Since there is no help for it, adopt java.util.List as the variable type

The easiest.

val statuses: ResponseList[Status] = twitter.getUserTimeline(paging)
val tweets: java.util.List[Tweet] = statuses
    .stream()
    .map(status => new Tweet(status.getId, status.getText, status.getUser.getName))
    .collect(Collectors.toList)

However, if the method returns the variable tweets, Scala's List is good! Because it's Scala.

2. Convert Java collection class to Scala collection class

According to the Scala documentation (https://docs.scala-lang.org/en/overviews/collections/conversions-between-java-and-scala-collections.html), Scala and Java collections are converted to each other. It seems that it can be done.

//JavaConverters class is responsible for converting collections
import scala.collection.JavaConverters._

val statuses: ResponseList[Status] = twitter.getUserTimeline(paging)
val tweets: List[Tweet] = statuses
      //ResponseList(Java) => mutable.Buffer(Scala)
      .asScala 
      //Then use the Scala collection operation API
      .map(status => new Tweet(status.getId, status.getText, status.getUser.getName))
      .toList

Supplement about Java Converters

Comparison table between Scala collections and Java collections

Scala Java
Iterator java.util.Iterator
Iterator java.util.Enumeration
Iterable java.lang.Iterable
Iterable java.util.Collection
mutable.Buffer java.util.List
mutable.Set java.util.Set
mutable.Map java.util.Map
mutable.ConcurrentMap java.util.concurrent.ConcurrentMap

How to use

It is possible to convert by declaring ʻimport collection.JavaConverters._ and then using ʻasJava method and ʻasScala` method. However, it seems that it is not all-purpose, so please use it with care. For more information, see Official Documentation

Reference URL

Convert collections between Scala Documentation JAVA and SCALA

Recommended Posts

I was addicted to using Java's Stream API in Scala
I was addicted to using RXTX on Sierra
A story I was addicted to when testing the API using MockMVC
I was addicted to starting sbt
What I was addicted to while using rspec on rails
I tried using Java8 Stream API
What I was addicted to with the Redmine REST API
I was addicted to the API version min23 setting of registerTorchCallback
I tried using Elasticsearch API in Java
Try using the Stream API in Java
I was addicted to rewriting to @SpringApplicationConfiguration-> @SpringBootTest
I was addicted to the roll method
I tried to summarize the Stream API
Memorandum: What I was addicted to when I hit the accounting freee API
[Rails] I was addicted to the nginx settings when using Action Cable.
I was addicted to unit testing with the buffer operator in RxJava
I was addicted to installing Ruby/Tk on MacOS
[Java] How to operate List using Stream API
SpringSecurity I was addicted to trying to log in with a hashed password (solved)
I was addicted to the record of the associated model
I tried using Google Cloud Vision API in Java
The part I was addicted to in "Introduction to Ajax in Java Web Applications" of NetBeans
I went to Scala Fukuoka 2019!
What I was addicted to when introducing the JNI library
I want to find a relative path in a situation using Path
What I fixed when updating to Spring Boot 1.5.12 ・ What I was addicted to
I was addicted to setting default_url_options with Rails devise introduction
I was addicted to looping the Update statement on MyBatis
Java Stream API in 5 minutes
A story I was addicted to before building a Ruby and Rails environment using Ubuntu (20.04.1 LTS)
I tried using Dapr in Java to facilitate microservice development
[Java] Introduction to Stream API
The story I was addicted to when setting up STS
[Circle CI] A story I was addicted to at Start Building
I can't log in to MySQL from Django when using docker-compose
A note when I was addicted to converting Ubuntu on WSL1 to WSL2
Let's consider the meaning of "stream" and "collect" in Java's Stream API.
About the matter that I was addicted to how to use hashmap
[java8] To understand the Stream API
[Introduction to Java] About Stream API
I tried using JWT in Java
Java 8 ~ Stream API ~ to start now
I summarized the points to note when using resources and resources in combination
My.cnf configuration problem that I was addicted to when I was touching MySQL 8.0 like 5.7
I was addicted to a simple test of Jedis (Java-> Redis library)
Problems I was addicted to when building the digdag environment with docker
Recorded because I was addicted to the standard input of the Scanner class
I was a little addicted to running old Ruby environment and old Rails
I was addicted to scrollview because I couldn't tap the variable size UIView
[CircleCI] I was addicted to the automatic test of CircleCI (rails + mysql) [Memo]
I called the COTOHA API parser 100 times in Java to measure performance.
I was a little addicted to ssh connection from mac to linux (ubuntu)
To you who were told "Don't use Stream API" in the field
When I wanted to create a method for Premium Friday, it was already in the Java 8 standard API
Data processing using stream API from Java 8
I tried using Java's diagnostic tool Arthas
Try using JSON format API in Java
Anonymous class (aiming to introduce stream api)
I want to use @Autowired in Servlet
Notes on Java's Stream API and SQL
Try adding text to an image in Scala using the Java standard library