Java Queries Here..

TheSloth

The Slowest One
Sorry, that was a force of habit. We use Java 8 at work, so I have developed a habit of using lambdas.
This is good. I also wanted to be like this but I am so much use to Java 7 that even when working with Java 8 I continue old practices because of which I have been struggling a lot lately.

@quicky008 One major advantage of baeldung is that the author uses latest java code so to understand the examples on that website, you need to first update your own java knowledge. I came across lambda expressions like that and was forced to learn that first before understanding the solution to my problem
I will suggest you also to refer coding practices in new java versions and use those as habit. Otherwise you will struggle like me.
 

Desmond

Destroy Erase Improve
Staff member
Admin
Lambdas are not very hard to learn. They are just functional interfaces that have a single method. Knowing when to use it will take some practice though. Start by learning Stream API in Java 8, this is one area where lambdas are used a lot.
 

TheSloth

The Slowest One
Yeah. I am working on 2 projects where one uses Java 8 ,so trying to use streams with filter wherever possible. To get more practiced, I should do some personal projects. Otherwise my work mostly involves Java 7.
 

quicky008

Technomancer
Somebody gave me this code,apparently its from a website called hackerrank:
Java:
import java.io.*;
import java.math.*;
import java.security.*;
import java.text.*;
import java.util.*;
import java.util.concurrent.*;
import java.util.function.*;
import java.util.regex.*;
import java.util.stream.*;
import static java.util.stream.Collectors.joining;
import static java.util.stream.Collectors.toList;

public class Solution {



    // Complete the findNumber function below.
    static String findNumber(List<Integer> arr, int k) {
        String answer = "NO";
        for (Integer i : arr) {
            if (i == k) {
                answer = "YES";
                break;
            }
        }
        return answer;
    }

    public static void main(String[] args) throws IOException {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(System.out));

        int arrCount = Integer.parseInt(bufferedReader.readLine().trim());

        List<String> arrTemp = new ArrayList<>();

        IntStream.range(0, arrCount).forEach(i -> {
            try {
                arrTemp.add(bufferedReader.readLine().replaceAll("\\s+$", ""));
            } catch (IOException ex) {
                throw new RuntimeException(ex);
            }
        });

        List<Integer> arr = arrTemp.stream()
            .map(String::trim)
            .map(Integer: parseInt)
            .collect(toList());

        int k = Integer.parseInt(bufferedReader.readLine().trim());

        String res = findNumber(arr, k);

        bufferedWriter.write(res);
        bufferedWriter.newLine();

        bufferedReader.close();
        bufferedWriter.close();
    }
};

I was asked to explain what's going on but i am quite confused regarding some of the things that are present in the above code.For instance,what's the significance of the following line:
arrTemp.add(bufferedReader.readLine().replaceAll("\\s+$", ""));

Also what do the foll. mean?

List<Integer> arr = arrTemp.stream()
.map(String::trim)
.map(Integer: parseInt)
.collect(toList())

Its clear that arr is a List of type integer,but why have they assigned arrTemp.stream() to it?Also what exactly is the purpose of .map and .collect?

Any explanations on the above would be greatly appreciated.Also is this website ie hackerrank a good place to improve one's understanding of core-java and prepare oneself for coding related interviews(esp. for folks who don't have extensive knowledge of programming)?
 
Last edited:

Desmond

Destroy Erase Improve
Staff member
Admin
For instance,what's the significance of the following line:
arrTemp.add(bufferedReader.readLine().replaceAll("\\s+$", ""));
It's adding each line to the array after removing whitespace from the end of the string. It's using regular expressions to identify the whitespaces.


Also what do the foll. mean?

List<Integer> arr = arrTemp.stream()
.map(String::trim)
.map(Integer: parseInt)
.collect(toList());

Its clear that arr is a List of type integer,but why have they assigned arrTemp.stream() to it?Also what exactly is the purpose of .map and .collect?
This is the Java 8 Stream API. You can use streams to chain operations on some collections such as on list. Here, the stream of the string array is being transformed into an integer stream and then collected into a list.

arrTemp.stream() creates a stream using the elements in this array.

The first map() trims each string (Now that I think of it, trim could be used instead of replaceAll above and this operation could have been avoided.)

The second map() transforms each string to integer.

Finally, the collect() consolidates the resultant elements, in this case into a list. There are many other collectors available that can consolidate in other ways.
 

Desmond

Destroy Erase Improve
Staff member
Admin
There is a lot of things wrong with the code though. For example BufferedReader is being used to write to STDOUT when you could simply use System.out.println(). Also, I'd personally use the Scanner class to read the lines rather than use BufferedReader for the same.
 

Desmond

Destroy Erase Improve
Staff member
Admin
What is the HackerRank problem statement that this is a solution for? Can you give me the link? This program seems way to complex for what it's meant to do.

I can see that it says // Complete the findNumber function below. which means that the main() method was already like that in the code but I find it hard to believe.
 

quicky008

Technomancer
i received it from someone i know,apparently he was given this question as a part of some kind of test round after applying for an internship with them.

This pdf details the entire problem,the "find the number" part was initially incomplete and the person taking this test was expected to solve it.

PS there are quite a few spelling and syntactical errors in the pdf as it was copied directly from their IDE,hopefully it will not affect the readability of the code.
 

Attachments

  • Find the number!.pdf
    47.6 KB · Views: 24

Desmond

Destroy Erase Improve
Staff member
Admin
i received it from someone i know,apparently he was given this question as a part of some kind of test round after applying for an internship with them.

This pdf details the entire problem,the "find the number" part was initially incomplete and the person taking this test was expected to solve it.

PS there are quite a few spelling and syntactical errors in the pdf as it was copied directly from their IDE,hopefully it will not affect the readability of the code.
Yeah, looks like the main() method is the same from the problem statement.

The solution is to simply implement the findNumber() method. As such I don't think you are expected to understand what's in the main() method since that simply runs the findNumber() method.
 
Modified the code to make it readable.

Ignore the predefined code as now, focus on the problem statement and if you are able to run the code as expected.

If you want to start in hackerrank, pick your favourite language and start here - Day 0: Hello, World. | HackerRank

Java:
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class Soultion {

    // Complete the findNumber function below.
    static String findNumber(List<Integer> arr, int k) {
        String answer = "NO";
        for (Integer i : arr) {
            if (i == k) {
                answer = "YES";
                break;
            }
        }
        return answer;
    }

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int arrLen = sc.nextInt();
        List<Integer> arr = new ArrayList<Integer>();
        for (int i = 0; i < arrLen; i++) {
            arr.add(sc.nextInt());
        }
        int k = sc.nextInt();
        String res = findNumber(arr, k);
        System.out.println(res);
        sc.close();
    }
}
 

Desmond

Destroy Erase Improve
Staff member
Admin
Yeah, I have not logged in in a long time now. I guess I will start again. Looks like a lot of new problems added since I last visited.
 

quicky008

Technomancer
@Desmond David :thanks for your in-depth reply,your explanations really helped me in understanding this rather abstruse piece of code.

@khalil1210: does having a high rank in these competitive programming websites improve one's chances of getting placed in a decent MNC?
 
@khalil1210: does having a high rank in these competitive programming websites improve one's chances of getting placed in a decent MNC?
It helped me to write code, improving problem solving skills and gain confidence. I never had any high rank, so can't comment on that part. I used to spend a lot of time on understanding the easy questions and writing a solution and running the test cases.

During my college my main problem was I understood the problem, was able to build a solution, but I was never able to put it as code and run the test cases. I landed in a internship in my last year in college, because we had multiple coding rounds and I was confident and was able to successfully run the code.

One of my friends during college got few interview calls based on their his profile ( 5 years back )

Another friend got a interview based on his hackerrank profile and secured the job. He had 3+ years experience ( 2 years back ).The company sent him a test link, it had 10 java multiple choice questions and one program. Though he was not able to successfully run all the test cases, he was selected and in interview they asked him about how he solved it.

Don't stress on getting a higher rank, focus on
  • data structures
    • what are different types of data structures
    • where we use them
    • why we use them
  • algorithms
    • sorting algorithms ( binary sort, merge sort )
    • search ( binary search )
    • Big O notation
    • Time complexity
    • space complexity

There are other sites as well

Programming Challenges, and Coding Competitions on HackerEarth - has hiring weekly challenges for Indian companies

LeetCode - The World's Leading Online Programming Learning Platform - This is paid, I haven't tried it. Students from US use this site for FAANG companies, not sure about India. very popular on reddit.

Other sites I like

Codeforces

 
Last edited:

TheSloth

The Slowest One
There is a lot of things wrong with the code though. For example BufferedReader is being used to write to STDOUT when you could simply use System.out.println(). Also, I'd personally use the Scanner class to read the lines rather than use BufferedReader for the same.
The code is from Hackerrank I guess. They have run all their test cases and match the output of the code against each test case, which are probably in some files. I am assuming this the reason they are using bufferedreader.
 

TheSloth

The Slowest One
@Desmond David :thanks for your in-depth reply,your explanations really helped me in understanding this rather abstruse piece of code.

@khalil1210: does having a high rank in these competitive programming websites improve one's chances of getting placed in a decent MNC?
Indirectly, Yes. Directly, may be.
Indirectly in way since you have been solving lots of problems and improving skills, there is no other way to gain high rank or more points.

You can practice these coding things always to stay in touch with coding but I suggest you read more about how to code, design patterns, algorithms to be better at coding. Coding practices on these sites will help you keep your pace in solving problems but they don't help in improving code standards and knowledge bank. Read a lot! If you are in college, then you must do that ! Later you might not find time to do extensive reading because of job and house related works.

A lot of companies conduct challenges on hackerearth, you can attend those on weekends to get used to coding in limited amount of time. Weekdays you can do normal problems.
There are lots of start up companies on @ngeL list who ask candidates to attend 1st round through Hackerrank or Hackerearth. So stick to these sites to stay in touch with current market evaluations.
 
Last edited:
Top Bottom