Skip to main content

Hackrank test sample api consumption java code sample


import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.HttpURLConnection;

import java.net.URL;

import java.util.*;

import java.util.regex.Matcher;

import java.util.regex.Pattern;


public class TransactionFetcher {


    public static List<double[]> getTransaction(int locationId, String txnType) {

        int page = 1;

        List<double[]> transactions = new ArrayList<>();


        while (true) {

            try {

                String urlString = "https://jsonmock.hackerrank.com/api/transactions/search?" +

                        "txnType=" + txnType + "&page=" + page;

                URL url = new URL(urlString);

                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("GET");


                BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));

                String inputLine;

                StringBuilder content = new StringBuilder();


                while ((inputLine = in.readLine()) != null) {

                    content.append(inputLine);

                }


                in.close();

                connection.disconnect();


                // Convert the response to JSON object

                Map<String, Object> response = new Gson().fromJson(content.toString(), Map.class);


                int totalPages = ((Double) response.get("total_pages")).intValue();

                List<Map<String, Object>> data = (List<Map<String, Object>>) response.get("data");


                for (Map<String, Object> value : data) {

                    Map<String, Object> location = (Map<String, Object>) value.get("location");

                    if (((Double) location.get("id")).intValue() == locationId) {

                        int userId = ((Double) value.get("userId")).intValue();


                        // Removing any non-numeric characters from the amount string

                        String amountString = (String) value.get("amount");

                        Pattern pattern = Pattern.compile("[^0-9.]");

                        Matcher matcher = pattern.matcher(amountString);

                        String amountCleaned = matcher.replaceAll("");

                        double amount = Double.parseDouble(amountCleaned);

                        amount = Math.round(amount * 100.0) / 100.0;


                        boolean found = false;

                        for (double[] transaction : transactions) {

                            if (transaction[0] == userId) {

                                transaction[1] += amount;

                                found = true;

                                break;

                            }

                        }


                        if (!found) {

                            transactions.add(new double[]{userId, amount});

                        }

                    }

                }


                if (page >= totalPages) {

                    break;

                }


                page++;

            } catch (Exception e) {

                e.printStackTrace();

            }

        }


        if (transactions.isEmpty()) {

            return Arrays.asList(new double[]{-1, -1});

        }


        transactions.sort(Comparator.comparingDouble(a -> a[0]));


        return transactions;

    }


    public static void main(String[] args) {

        List<double[]> result = getTransaction(1, "debit");


        for (double[] transaction : result) {

            System.out.println("UserId: " + (int) transaction[0] + ", Amount: " + transaction[1]);

        }

    }

}


Comments

Popular posts from this blog

Learning How to Map One-to-Many Relationships in JPA Spring Boot with PostgreSQL

  Introduction In this blog post, we explore how to effectively map one-to-many relationships using Spring Boot and PostgreSQL. This relationship type is common in database design, where one entity (e.g., a post) can have multiple related entities (e.g., comments). We'll dive into the implementation details with code snippets and provide insights into best practices. Understanding One-to-Many Relationships A one-to-many relationship signifies that one entity instance can be associated with multiple instances of another entity. In our case: Post Entity : Represents a blog post with fields such as id , title , content , and a collection of comments . Comment Entity : Represents comments on posts, including fields like id , content , and a reference to the post it belongs to. Mapping with Spring Boot and PostgreSQL Let's examine how we define and manage this relationship in our Spring Boot application: Post Entity  @Entity @Getter @Setter @Builder @AllArgsConstructor @NoArgsCons

Tree Based Common problems and patterns

  Find the height of the tree. public class BinaryTreeHeight { public static int heightOfBinaryTree (TreeNode root) { if (root == null ) { return - 1 ; // Height of an empty tree is -1 } int leftHeight = heightOfBinaryTree(root.left); int rightHeight = heightOfBinaryTree(root.right); // Height of the tree is the maximum of left and right subtree heights plus 1 for the root return Math.max(leftHeight, rightHeight) + 1 ; } Find the Level of the Node. private static int findLevel (TreeNode root, TreeNode node, int level) { if (root == null ) { return - 1 ; // Node not found, return -1 } if (root == node) { return level; // Node found, return current level } // Check left subtree int leftLevel = findLevel(root.left, node, level + 1 ); if (leftLevel != - 1 ) { return leftLevel; // Node found in t

Stay Updated As Software Engineer

Are you a software engineer looking to stay updated and grow in your field? We've got you covered with over 50 valuable resources to keep you on the cutting edge of technology. From newsletters to books, we've curated a diverse list just for you.   Newsletters:   Pragmatic Engineer: Link   TLDR: Link   Level-up software engineering: Link   Coding challenges: Link   Engineers Codex: Link   Techlead Mentor: Link   Saiyan Growth letter: Link   Wes Kao: Link   Addy Osmani: Link   And many more (see link below)   Books:   Engineering:   A Philosophy of Software Design Link   Clean Code Link   Communication & Soft Skills:   Smart Brevity Link   Connect: Building Exceptional Relationships Link   Crucial Conversations Link   Engineers Survival Guide Link   Leadership:   The Manager's Path Link   Staff Engineer: Leadership Beyond the Management Track Link   The Coaching Habit: Say Less, Ask More Link   While we can't list all 50+ resources here, this is a fantastic sta