Can lambda expressions in java be still compacted - java

I have this code.
public class TypeInterface{
public static void main(String [] args){
StringLengthLambda myLambda = s -> s.length();
System.out.print(myLambda.getLength("abc"));
}
interface StringLengthLamdba{
int getLength(String s);
}
}
Can this code be modified to
StringLengthLambda myLambda = s.length()
or
any other way to shorten this?

I can't think of any way to write a shorter lambda, but you could use a method reference:
StringLengthLambda myLambda = String::length;

You don't even need the package protected interface StringLengthLambda. You could just go with:
public static void main(String [] args){
Function<String, Integer> myLambda = String::length;
System.out.print(myLambda.apply("abc"));
}
If you want different "length-computation-methods" on "abc" you could even go with:
public class TypeInterface {
public static void main(String[] args) {
print(String::length);
}
private static void print(StringLengthLambda myLambda) {
System.out.print(myLambda.getLength("abc"));
}
#FunctionalInterface
interface StringLengthLambda {
int getLength(String s);
}
}

Related

Cannot find symbol of written method java.util.function

I have code like
public class Functionz {
public static boolean test() {
return true;
}
public static void main(String[] args) {
Function[] funcs = new Function[] {test}; // and others
for (Function func : funcs) {
func();
}
}
}
and my error is: cannot find symbol: test in the line with the function array declaration.
Hope this isn't a stupid question, very new to java, not new to object oriented languages like python and C++.
A Function in Java does takes one parameter as input and one as output.
You might declare parameter's type this way : Function<Integer, String> is a function that transforms an Integer into a String
Your method test() does not take any input value and outputs a boolean so it's a Supplier.
import java.util.function.Supplier;
public class Main {
public static boolean test() {
System.out.println("lorem ipsum");
return true;
}
public static void main(String[] args) {
Supplier[] funcs = new Supplier[] {Main::test}; // and others
for (Supplier func : funcs) {
func.get();
}
}
}
Your code would compile if test requires one (and only one parameter) like
import java.util.function.Function;
public class Main {
public static boolean test(String str) {
System.out.println(str);
return true;
}
public static void main(String[] args) {
Function[] funcs = new Function[] {(Object anyObject) -> test(anyObject.toString())}; // and others
for (Function func : funcs) {
func.apply("lorem ipsum");
}
}
}
Here's the list of those types
Please note that Function doesn't type its parameters in construction because you can't create arrays with generic type in Java (you might for specific usecases) => Use a List will help you here

error - : incompatible types: possible lossy conversion from int to short

I know this error occurs when we try downcasting values but in my code I am not able to figure ooout where have I downcasted the values.
class TestClass {
public static void main(String args[] ) throws Exception {
TestDemo obj=new TestDemo();
TestDemo2 obj1= new TestDemo2();
obj.show(5);
obj1.show("helloworld");
}
}
class TestDemo{
public void show(short N){
System.out.println(N*2);
}
}
class TestDemo2{
public Void show(String S){
System.out.println(S);
}
}
This error is occurring due to obj.show(5).
Two fixes`you can do any:
class TestClass {
public static void main(String args[] ) throws Exception {
TestDemo obj=new TestDemo();
TestDemo2 obj1= new TestDemo2();
obj.show((short)5);
obj1.show("helloworld");
}
}
class TestDemo{
public void show(short i){
System.out.println(i*2);
}
}
class TestDemo2{
public void show(String S){
System.out.println(S);
}
}
Second Version
class TestClass {
public static void main(String args[] ) throws Exception {
TestDemo obj=new TestDemo();
TestDemo2 obj1= new TestDemo2();
obj.show(5);
obj1.show("helloworld");
}
}
class TestDemo{
public void show(int i){
System.out.println(i*2);
}
}
class TestDemo2{
public void show(String S){
System.out.println(S);
}
}
Try changing the short N, in public void show(short N) from test Demo to int.
try to cast the int first.
obj.show((short)5);
Number 5 is treated by default as integer which is passed to method with short argument.
obj.show((short)5);
Also for future reference, java errors as well as exceptions are very detailed, giving you the exact line number where the issue occurred. That should help you identify the code segment where the issue is.

Java Integer class code not compiling

I am new to Java.
I am Learning Wrapper class now from Online Resources
The following code does not compile but according to the online material this is giving results
class Integ
{
public static void main(String[] args)
{
Integer I=new Integer.valueOf("1111",2);
System.out.println(I);
}
}
Can you please correct me where i am going wrong.
class Integ
{
public static void main(String[] args)
{
Integer i = Integer.valueOf("1111", 2);
System.out.println(i);
}
}
dont use the new operator, just do Integer.valueOf("1111",2);
public static void main(String[] args)
{
Integer myI = new Integer.valueOf("1111",2);
// ^^^
System.out.println(I);
}
do instead:
public static void main(String[] args)
{
Integer myI = Integer.valueOf("1111",2);
// ^^^
System.out.println(I);
}
You're not supposed to use new. Just remove it:
Integer I = Integer.valueOf("1111",2);

Declaration for an array being called into main from a method (Java)

I am fairly new to java, and am having what I assume is a simple problem with my program.
For the method arrayTest2, I cannot import it into main due to an error on compilation:
"Cannot find symbol, symbol: variable dataStorage".
I have tried also tried the declarations:
arrayTest2(dataStorage[][])
and
arrayTest2(dataStorage[5][5])`
but they don't work.
Any help would be greatly appreciated.
Cheers
import io.*;
public class TrialArray
{
public static void main(String [] args)
{
arrayTest();
arrayTest2(dataStorage);
}
public static void arrayTest()
{
int[][] dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}
The problem here is the scope: Something defined in one function is not visible in another. What you will normally do to solve this is to return the value. Something like this:
import io.*;
public class TrialArray
{
public static void main(String [] args)
{
int[][] dataStorage = arrayTest();
arrayTest2(dataStorage);
}
public static int[][] arrayTest()
{
int[][] dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
return dataStorage;
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}
Alternatively you could have your dataStorage field as a global variable, this is however potentially very confusing. To do that you'd define
public class TrialArray
{
private static int[][] dataStorage;
// ...
public static void arrayTest() {
dataStorage = new int[5][5];
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
// ...
}
on this line
arrayTest2(dataStorage);
You are passing parameter to method, that has one argument "dataStorage", but you don't declare it.
You try to pass dataStorage to your arrayTest-function, but dataStorage is not a field of the class, neither is it a local variable of main (aka dataStorage does not exist in main).
public static void main(String [] args) {
arrayTest();
arrayTest2(dataStorage); //<------- What is dataStorage?
}
Here is a little tutorial on variable scopes in Java. You probably want to return the array you created in arrayTest() and use it, but I am just guessing what you want to do.
You cant access variables in declared inside other methods.
To make it work, you would have to do this:
public class TrialArray
{
int[][] dataStorage;
public static void main(String [] args)
{
dataStorage = new int[5][5];
arrayTest();
arrayTest2(dataStorage);
}
public static void arrayTest()
{
dataStorage[1][2] = 1;
System.out.printf("THIS PART WORKS");
}
public static void arrayTest2(int[][] dataStorage)
{
dataStorage[2][2] = 3;
System.out.printf("THIS DOESNT");
}
}

Represent a Java type as a varargs

Is it possible to do something like this using Java features?
class myClass {int i; String s;}
static void myMethod(myClass... args)
{
...
}
main()
{
myMethod(2,"two",3,"three");
}
It is not possible. Perhaps you could create a static helper method which makes creating your objects as easy as possible.
static myClass mc(int i, String s) {
return new myClass(i, s);
}
myMethod(mc(2, "two"), mc(3, "three"));
No, but you can make a constructor of MyClass and invoke:
myMethod(new MyClass(2, "two"), new Myclass(3, "three"));
For the sake of brevity you can make a statically-imported factory method:
public class MyClass {
public MyClass create(String s, int i) {
return new MyClass(s, i);
}
}
and use:
myMethod(create(2, "two"), create(3, "three"));
You could do it with a wrapper class:
class MyWrapper {
private int i;
private String s;
public MyWrapper(int _i, String _s) {
i = _i;
s = _s;
}
}
class Test {
static void myMethod(MyWrapper... args) {
//do work
}
public static void main(String[] args) {
myMethod(new MyWrapper(2, "two"), new MyWrapper(3, "three"));
}
}
Yes, sortof. You need a constructor of your class...
public class MyClass{
int i
String s;
public MyClass(int i, String s){
this.i = i;
this.s = s;
}
}
public static void myMethod(MyClass... instances){
.....
}
public static void myMethod(Object... args){
MyClass[] instances = new MyClass[args.length / 2];
for (int i=0; i<args.length / 2; i++){
instances[i] = new MyClass((Integer)args[i * 2], (String)args[(i*2) + 1]);
}
myMethod(instances);
}
You would need to add error checking to ensure that args has an even number of elements and there is not a method to enforce that every i * 2 element is an Integer and every i * 2 + 1 is a String. But it is possible.
Given all of the above, I will say... this is very non-standard programming and I would not recommend it. But as you see, it is possible.

Categories

Resources