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

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

12 Must-Know LeetCode+ Links for Coding Excellence

Introduction: Welcome to a comprehensive guide on mastering essential coding techniques and strategies! Whether you're a beginner or an experienced coder, these LeetCode+ links will elevate your skills and make you a more proficient problem solver. Let's dive into the world of algorithms, data structures, and coding patterns that will empower you to tackle complex challenges with confidence. 1. Sliding Window Learn the art of efficient sliding window techniques: Sliding Window - Part 1 and Sliding Window - Part 2 . Enhance your coding prowess and optimize algorithms with these invaluable insights. 2. Backtracking Unlock the power of backtracking algorithms: Backtracking . Discover how to systematically explore possibilities and find optimal solutions to a variety of problems. 3. Greedy Algorithm Master the art of making locally optimal choices for a globally optimal solution: Greedy Algorithm . Dive into strategies that prioritize immediate gains and lead to optimal outcomes

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