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

Mastering Java Logging: A Guide to Debug, Info, Warn, and Error Levels

Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Comprehensive Guide to Java Logging Levels: Trace, Debug, Info, Warn, Error, and Fatal Logging is an essential aspect of application development and maintenance. It helps developers track application behavior and troubleshoot issues effectively. Java provides various logging levels to categorize messages based on their severity and purpose. This article covers all major logging levels: Trace , Debug , Info , Warn , Error , and Fatal , along with how these levels impact log printing. 1. Trace The Trace level is the most detailed logging level. It is typically used for granular debugging, such as tracking every method call or step in a complex computation. Use this level sparingly, as it ...

Advanced Kafka Resilience: Dead-Letter Queues, Circuit Breakers, and Exactly-Once Delivery

Introduction In distributed systems, failures are inevitable—network partitions, broker crashes, or consumer lag can disrupt data flow. While retries help recover from transient issues, you need stronger guarantees for mission-critical systems. This guide covers three advanced Kafka resilience patterns: Dead-Letter Queues (DLQs) – Handle poison pills and unprocessable messages. Circuit Breakers – Prevent cascading failures when Kafka is unhealthy. Exactly-Once Delivery – Avoid duplicates in financial/transactional systems. Let's dive in! 1. Dead-Letter Queues (DLQs) in Kafka What is a DLQ? A dedicated Kafka topic where "failed" messages are sent after max retries (e.g., malformed payloads, unrecoverable errors). ...