I was trying to convert a lambda expression into method reference, but I failed to do so.
can anybody help me with this?
The lambda expression takes 2 int parameters adds it and return the result.
public class Addition {
public static void main(String[] args) {
int a = 10;
int b = 20;
A ref = (int c, int d) -> c + d;
System.out.println(ref.add(a, b));
}
}
Based on the signature of the method implemented by your lambda expression, you can replace it with:
A ref = Integer::sum;
Since that sum method accepts two int arguments and returns their int sum:
public static int sum(int a, int b) {
return a + b;
}
Related
I am writing code in Java which has multiple methods and these methods have multiple variables. I want the other methods to access the variables of another method using actual and formal parameters. How can I do it?
I am pasting an example of the problem I'm facing.
Error : variable is not defined.
Code
public class example {
public void addition() {
int a = 0;
int b = 10;
int c = a + b;
}
public void result() {
System.out.println("The result for the above addition is" + c);
}
}
IM GETTING AN ERROR SAYING VARIABLE IS NOT DEFINED
You should declare c as global variable
public class Example {
int c;
public void addition() {
int a = 0;
int b = 10;
c = a + b;
}
public void result() {
System.out.println("The result for the above addition is " + c);
}
public static void main(String[] args) {
Example e = new Example();
e.addition();
e.result();
}
}
well, your java syntax is quite wrong... if you need to do an addition, you can do as follows:
public class Addition {
public static int addition(int a, int b)
{
int c= a + b;
return c;
}
public static void main(String[] args) {
int a = 1;
int b = 10;
int c = addition(a,b);
System.out.println("The result for the above addition is " + c);
}
}
where addition function does add a + b and return the result to your main method.
I am exploring both scala and Java 1.8 but unable to find equivalent code in with java 1.8 lambda expressions.
Scala code:
object Ex1 extends App {
def single(x:Int):Int =x
def square(x:Int):Int = x * x
def cube(x:Int):Int = x*x*x
def sum(f:Int=>Int,a:Int,b:Int):Int=if (a>b) 0 else f(a) + sum(f,a+1,b)
def sumOfIntegers(a:Int,b:Int)=sum(single,a,b)
def sumOfSquares(a:Int,b:Int)=sum(square,a,b);
def sumOfCubes(a:Int,b:Int)=sum(cube,a,b);
println(sumOfIntegers(1,4));
println(sumOfSquares(1,4));
println(sumOfCubes(1,4));
}
output:
10
30
100
java:
public class Test1{
public int single(int x){
return x;
}
public int square(int x){
return x * x;
}
public int cube(int x){
return x * x * x;
}
// what's next? How to implement sum() method as shown in Scala?
// Stuck in definition of this method, Stirng s should be function type.
public int sum( Sring s , int a, int b){
// what will go here?
}
public int sumOfIntegers(int a, int b){
return sum("single<Function> how to pass?",a,b);
}
public int sumOfSquares(int a, int b){
return sum("square<Function> how to pass?",a,b);
}
public int sumOfCubes(int a, int b){
return sum("cube<Function> how to pass?",a.b);
}
}
Is it possible to achieve the same with JDK 1.8?
You are going to need to define the methods that you are going to use. The only one that comes with Java is the Function<X,Y> which (with Integer) can be used for single, square and cube and BiFunction<T,Y, R> which can be used for the three sumOfs.
interface Sum {
Integer apply(Function<Integer, Integer> func, int start, int end);
}
The single, square and cube could be either methods in the class (see cube or inline (see the other two). They are Fuctions. This function can then be passed to other methods and called with variableName.apply.
class Test
{
private static Integer sum(Function<Integer, Integer> func, int a, int b) {
if (a>b)
return 0;
else return func.apply(a) + sum(func,a+1,b);
}
private static Integer cube(Integer a) {
return a * a * a;
}
public static void main (String[] args) throws java.lang.Exception
{
Function<Integer,Integer> single = a -> a;
Function<Integer,Integer> square = a -> a * a;
Function<Integer,Integer> cube = Test::cube;
// You can not do the sum in-line without pain due to its recursive nature.
Sum sum = Test::sum;
BiFunction<Integer, Integer, Integer> sumOfIntegers = (a, b) -> sum.apply(single, a, b);
BiFunction<Integer, Integer, Integer> sumOfSquares = (a, b) -> sum(square, a, b); // You could just use the static method directly.
BiFunction<Integer, Integer, Integer> sumOfCubes = (a, b) -> sum(cube, a, b);
System.out.println(sumOfIntegers.apply(1,4));
System.out.println(sumOfSquares.apply(1,4));
System.out.println(sumOfCubes.apply(1,4));
}
}
Yes, it is possible:
public Integer sumSingle(Integer a) { return a; }
public int sum(Function<Integer, Integer> f, int a, int b)
{
... : f.apply(a+1); // or whatever
}
public int sumOfIntegers(int a, int b)
{
return sum(Test1::single, a, b);
}
The construct Class::method creates a Function object from the method. Or if you don't need to reuse it, you can directly pass an argument instead: (Integer a) -> a*a* ...
Function<Integer, Integer> single = x -> x;
Function<Integer, Integer> square = x -> x*x;
public int sum( Function<Integer, Integer> s , int a, int b){
if (a>b){
return 0;
} else {
s.apply(a) + sum(s,a+1,b)
}
}
In Java 8 you can use any functional interface, i.e. an interface with exactly one non-static method without a default implementation, in place of Scala's Function<N> types. There are quite a few such interfaces in the java.util.function package, for single-argument and two-argument functions; in particular for functions which take and return int you should use IntUnaryOperator, already mentioned in other people's comments. If you have more than two arguments, or two arguments of different types, define your own interface with one method. E.g. for functions of 3 arguments which take int, long and long and return a non-primitive:
interface Fun3ILLO<T> {
public T apply(int arg1, long arg2, long arg3);
}
(obviously you can choose the interface and method name you want).
This is one of the practice questions of a test:
Write a method which accepts two integer values as input parameters and returns the boolean result true if the sum of the inputs is greater than or equal to 10 (and falseotherwise)
My answer is below but I don't think it looks correct. Can anyone give me a pointer?
public class Bruh{
public static void main (String [] arg){
int a;
int b;
boolean sum = true;
if ( a+b > 10)
System.out.println ("yo");
else{
sum = false;
}
}
}
You only wrote some code in the main method but you did not create one.
In order to do that you need to actually create a method in your Bruh class like:
public static boolean isSumGreaterThan9(int a, int b){
return (a + b) > 9;
}
Than call it from the main method:
public static void main (String [] arg){
int a = 4; // or whatever
int b = 7; // or whatever
System.out.println(isSumGreaterThan9(a, b));
}
You need to put your logic into a method and change your comparison to >= as per the requirement:
public static boolean isSumGreaterThanOrEqualToTen(int a, int b) {
return (a + b) >= 10;
}
I have a program to find pythagorean triples. in it, i have an object that needs to be used to call methods. Said object is broken. Errors are " The method Triples(int) is undefined for the type Triples" and "The method greatesCommonFactor() is undefined for the type Triples" mind you, not everything in Triples does useful stuff atm. It isn't completely finished yet.
public class TriplesRunner
{
public static void main(String args[])
{
int number;
Scanner keyboard = new Scanner(System.in);
System.out.print("Enter the natural number :: ");
number=keyboard.nextInt();
Triples test = new Triples();
test.Triples(number);
test.greatestCommonFactor(number);
System.out.println(test.toString());
}
}
public class Triples
{
public int number;
public Triples(int num)
{
setNum(number);
}
public void setNum(int num)
{
int a = 0;
int b = 0;
int c = 0;
}
public int greatestCommonFactor(int a, int b, int c)
{
int max = 0;
for(a=1; a<=number-2; a++)
{
for(b=a+1; b<=number-1; b++)
{
for(c=b+1; c<=number; c++)
{
if(a*a + b*b == c*c);
}
}
}
return 1;
}
public String toString()
{
String output="";
output+="a + b + c";
return output+"\n";
}
}
you are trying to call the constructor as a method,
Change this part:
Triples test = new Triples();
test.Triples(number);
to
Triples.test = new Triples(number);
Triples isn't a method - it's your constructor, meaning it's invoked with the new operator:
Triples test = new Triples(number);
greatestCommonFactor is not defined properly. It currently takes three int arguments, instead of taking none and using Triples' data members:
public int greatestCommonFactor()
Can you help me find my error?
I'm trying to use these two methods here but my output is not working.
class Nine {
public static void Nine(String[] args) {
int x,y,z;
y = 3;
x = 7;
z = addEm(a, b);
System.out.println("answer= " +x);
}
public static addEm (double a, double b){
int c;
c = a+b;
}
}
Actually there are a lot of error in your code:
z=addEm(a, b);
here a and b are meaningless, you should use z=addEm(y,x); (if your intent is to sum three with seven)
System.out.println("answer= " +x);
I guess that you want to show the the results of the sum, therefore you should print z (and not x), so you should substitute with System.out.println("answer= " +z);
public static addEm (double a, double b) {
Here you missed the return type, and you need to consider also the type of parameters a and b. Since y,x and z are int, it is better if also a and b are int, and therefore specify also the return type as int:
public static int addEm (int a, int b) {
Or you can declare everything (y,x,z,a,b and return type) as a double: the important here is that they should be all of the same type. Moreover you miss also the return statement of the function addEm, that summarizing becomes:
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
And finally also the function
public static void Nine(String[] args)
it is not right named for an entry point: its names should be main.
So in conclusion, if you apply all the fix (by modifying as less as possible your original code) a code that compile, run and works following some 'logic' is:
class Nine {
public static void main(String[] args) {
int x, y, z;
y = 3;
x = 7;
z = addEm(y, x);
System.out.println("answer= " + z);
}
public static int addEm(int a, int b) {
int c;
c = a + b;
return (c);
}
}
Man, this is a very basic java lesson:
every prog need an entry point, which is in java:
public static void main(String args[]){}
And then your code will execute.
You're passing arguments a and b to addEm, but those variables aren't initialized. I'm expecting you wanted to pass x and y instead.
class Nine
{
public static void Nine(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " +x);
}
public static addEm (double a, double b)
{
int c;
c=a+b;
}
}
Your code will not work because your addEm method does not have any return type. In addition, the method you wrote takes Double params but while using you are trying to pass int to it. You also do not have any main method. I am assuming you misspelled or misunderstood the main method so below is the code which should work
class Nine
{
public static void Main(String[] args)
{
int x,y,z;
y=3;
x=7;
z=addEm(x, y);
System.out.println("answer= " + x);
}
public static int addEm (int a, int b)
{
int c;
c=a+b;
return c;
}
}