Implementation of Java and Scala Creating List and Map
- 2021-11-24 01:40:13
- OfStack
Directory Java vs. Scala Create List vs. MapJava Custom map vs. scala map Comparison 1. Background 2. java Code
Java and Scala create List and Map
//Java
List<String> languages = new ArrayList<>();
Map<String, Class> mapFields = new HashMap();
//Scala
val languages = new util.ArrayList[String]
val mapFields=new util.HashMap[String, Class]
Comparison between Java Custom map and scala map
1. Background
In the process of learning scala, it is inevitable to compare java with scala. In this paper, map based on scala is implemented by java In jdk 1.8, Stream and lambda expressions are introduced, which makes java also support functional programming.
2. java code
2.1 Custom Implementation of map
package com.doit.udf;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
/**
* @author hulc
* @slogan: just do it
* @date 2020/9/13 21:16
*/
public class UserDefineFunc {
public static void main(String[] args) {
test1();
}
private static void test1() {
// Use java To realize scala Object for the collection in the map , reduce , filter Effect of function
List<Integer> list = new ArrayList<>();
list.addAll(Arrays.asList(1,2,3,4,5,6,7,8,9));
MyList<Integer> integers = new MyList<Integer>(list);
// Customize using anonymous inner classes map Method invocation
List<Object> list1 = integers.map(new MyMapFunction() {
@Override
public <String, K> String map(K k) {
if (k instanceof Integer) {
Integer i = (Integer) k;
i += 10;
return (String) ("" + i);
}
return null;
}
});
for (Object o : list1) {
System.out.println(o.toString());
}
}
}
class MyList<T> extends ArrayList<T> {
private List<T> words;
public MyList(List<T> words) {
this.words = words;
}
public List<Object> map(MyMapFunction function) {
List<Object> ts = new ArrayList<>();
for (T t : words) {
Object map = function.map(t);
ts.add(map);
}
return ts;
}
}
interface MyMapFunction {
// map Is 1 Conversion function, input 1 A K Convert to 1 A T
<T, K> T map(K k);
}
2.2 Functional processing using Sream of jdk
private static void test2() {
List<Integer> list = new ArrayList<>();
list.addAll(Arrays.asList(1,2,3,4,5,6,7,8,9));
// Will list Convert to Stream , then you can use functional expression to process
Stream<Integer> integerStream = list.stream();
Stream<String> stringStream = integerStream.map(w -> {
w += 10;
return "" + w;
});
// Traversal printing
Object[] toArray = stringStream.toArray();
for (Object o : toArray) {
System.out.println(o.toString());
}
}