2022-12-15
Useful Java Patterns

java stream guide

learn java and kotlin the same time?

beanshell syntax highlight seems to be rare. beanshell workspace has the highlight.

use v2.1.1 and above for varargs support.

there are eclipse and jetbrains plugin support for beanshell.

creating lists

1
2
3
4
5
6
7
8
var a = new ArrayList<>(Arrays.asList(1,2,3));
var mset = new HashSet<>();
mset.addAll(a);
var mset2 = a.stream().collect(Collectors.toSet());
var mymin = Collections.min(a);
var mymax = Collections.max(a);
Collections.reverse(a);

1
2
3
4
5
6
var a = arrayOf(1,2,3);
print(a.contentToString())
print(a.max())
print(a.min())
a.reverse()

creating hashmap

1
2
3
var ah= new HashMap<>();
ah.put(1,2);

1
2
var ah = hashMapOf(1 to 2, 2 to 3)

iterate lists with indices

java double colon :: operator acts as anonymous function

1
2
3
4
5
6
7
8
9
10
11
12
var l = a.listIterator();
while (l.hasNext()){
var index = l.nextIndex();
var val = l.next();
System.out.println("INDEX: "+index+" ELEM: "+val);
}
IntStream.range(0,a.size()).forEach(index -> a.get(index));
var index=0;
for (int i: a){
index++;
}

1
2
3
4
5
6
7
8
9
a.forEachIndexed{ind, elem -> println("index? $ind"); println("elem? $elem")}
for (var i in a.indices){
var elem = a[i]
}
a.indices.forEach {
var elem = a[it]
elem
}

list comprehension

1
2
3
4
var mlist = a.stream().map(x-> x*2).collect(Collectors.toList());
var evenNums = a.stream().filter(x-> x%2 == 0).collect(Collectors.toList());
var mmap = a.stream().collect(Collectors.toMap(x->x.getId(),x->x.getName()));

switch expressions

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var val = 2;
var mswitch = switch (val){
case 1,2,3 -> {
yield "good";
}
case 4,5,6 -> {
yield "bad";
} // either throw or yield.
default -> {
System.out.println("out of expectation");
yield "really bad";
}
};
System.out.println(mswitch);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var grade = 30
var res = when(grade) {
in 0..40 -> "Fail"
in 41..70 -> "Pass"
in 71..100 -> "Distinction"
else -> false
}
print(res)
var mcase = 1
var res = when(mcase){
1 -> "good"
2 -> "bad"
else -> "really bad"
}
print(res)

count occurance of elements in array

1
2
3
4
5
6
7
8
9
10
11
12
String[] array = {"name1","name2","name3","name4", "name5", "name2"};
Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s))
.forEach((k, v) -> System.out.println(k+" "+v.size()));
List asList = Arrays.asList(array);
Set<String> mySet = new HashSet<String>(asList);
for(String s: mySet){
System.out.println(s + " " + Collections.frequency(asList,s));
}
Map<String, Long> map = Arrays.stream(array)
.collect(Collectors.groupingBy(s -> s, Collectors.counting()));

1
2
3
var a = arrayOf(1,2,3,3,3,3)
a.toSet().forEach{it -> println("elem? $it"); println("count? "+a.count{it2->it2 == it})}

lambdas

1
2
3
4
5
6
Consumer mcons = (n) -> {System.out.println(n);}
mcons.andThen(mcons).accept("mval");
Function <Integer,Integer> mfunc = n-> n+1;
Supplier msup = () -> 1;
var mval = msup.get();

1
2
3
var mfunc = {n :Int -> n+1}
var mprint = {n:Any -> print(n)}

Read More

2022-09-08
Calling Java From Python

using jpype or pyjnius

sample code for jpype:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from jpype import *
import jpype.imports # this is needed! shit.
addClassPath("/root/Desktop/works/pyjom/tests/karaoke_effects/classpath/lingua.jar")
startJVM(getDefaultJVMPath())
java.lang.System.out.println("Calling Java Print from Python using Jpype!")
from com.github.pemistahl.lingua.api import *
# detector = LanguageDetectorBuilder.fromAllLanguages().withLowAccuracyMode().build()
detector = LanguageDetectorBuilder.fromAllLanguages().build() # 3.5GB just for detecting language! it is somehow crazy.
sample = 'hello world'
result = detector.detectLanguageOf(sample)
print(result, type(result)) # <java class 'com.github.pemistahl.lingua.api.Language'>
# but we can convert it into string.
strResult = str(result)
print(strResult, type(strResult))
import math
print("CALLING MATH: %d" % math.sqrt(4))
shutdownJVM()

sample for pyjnius:

1
2
3
4
5
6
7
8
9
10
11
12
13
import jnius_config
# jnius_config.add_options('-Xrs', '-Xmx4096')
jnius_config.set_classpath('.', "/root/Desktop/works/pyjom/tests/karaoke_effects/classpath/lingua.jar")
import jnius
jnius.autoclass('java.lang.System').out.println('Hello world')
detector = jnius.autoclass('com.github.pemistahl.lingua.api.LanguageDetectorBuilder').fromAllLanguages().build()
sample = 'hello world'
result = detector.detectLanguageOf(sample)
print(result, type(result))
# breakpoint()
strResult = result.toString()
print(strResult, type(strResult))

Read More