-1

Sorry, I'm totally new to Java. I'm trying to count the same URLs present in objects and I'm not able to figure out how to count them.

I was reading this article https://www.geeksforgeeks.org/passing-and-returning-objects-in-java/ and wondered if this is a way to count URLs object or another way. I'm stuck here for two days.

Can anyone please guide me?

class Main() {

  private HashMap<String, String> keyMap;
  private static int count = 0;

  public String newUrl(String url) { 
    //Completed: if the url is present in HashMap then return shortUrl else add it and return shortUrl
    return shortUrl
  } 

  public Integer countURL(String url){
    //int count = Collections.frequency(keyMap.values(), url);
    return count;
  }

  public static void main(String args[]) {
    Main a = new Main();
    
    String url = a.newUrl("http://example.com");
    String url1 = a.newUrl("http://example2.com");
    String url2 = a.newUrl("http://example2.com");
    System.out.println(url);
    System.out.println(url1);
    System.out.println(url2);;
    System.out.println(a.countURL("http://example2.com")); //2 if not then 0
   }
}
Happy
  • 23
  • 4
  • There is similar problem for strings in array https://stackoverflow.com/questions/40939301/counting-same-strings-from-array-in-java – Jan Přívratský Aug 21 '22 at 13:20
  • Your code doesn't compile, and this, `public String newUrl(String url) { return shorturl }` doesn't make sense. Your question seems to be, "how do I use a HashMap", but I'm not sure, and we don't know what key you're wanting to use, or what your complete requirements. Please avoid posting information that doesn't help us understand the question, such as, *"I've been stuck for days..."*, but instead, please show information that helps us better understand your problem, including your complete requirements. Also, please try to only post code that actually compiles. – Hovercraft Full Of Eels Aug 21 '22 at 13:24
  • Also, how does your current code and question relate to the tutorial link that you posted in your question? – Hovercraft Full Of Eels Aug 21 '22 at 13:27

1 Answers1

0

You can add this to your newUrl method:

public String newUrl(String url){
    if (!keyMap.containsKey(url)) {
        keyMap.put(url, 1);
        return url;
    }else {
        keyMap.replace(url, keyMap.get(url));
        return url;
    }
    
}

and in your countUrl method you can just return keyMap.get(url)

public Integer countURL(String url){
    return keyMap.get(url);
}