India’s Best Job Seekers and Training Platform Forums Java Problems set Given a file (which can be considered as a String…

  • Given a file (which can be considered as a String…

     Akash  updated 10 months, 1 week ago 2 Members · 2 Posts
  • Akash 

    Administrator
    at

    Given a file (which can be considered as a String with comma delimiter for the complexity of the question) of usernames and a value k, find top k usernames (with number of logins) who logged into the system the most.

    For example –

    Input:

    User (String) = user1, user4, user2, user1, user3, user1, user2, user3

    k (int) = 2

    Output:

    user1 (3)

    user2 (2)

    user3 (2)

    – Both user2 and user3 should be included since both has same number of logins

    Write a java method to find the output with best time and space complexity.

  • Akash 

    Administrator
    at

    package myProject;

    import java.awt.color.CMMException;

    import java.util.ArrayList;

    import java.util.Collections;

    import java.util.Comparator;

    import java.util.HashMap;

    import java.util.List;

    import java.util.Map.Entry;

    public class MaximumNumberOfusersLoggedin {

    public static void main(String[] args) {

    // TODO Auto-generated method stub

    String users = “user1, user4, user2, user1, user3, user1, user2, user3”;

    int k = 3;

    HashMap<String, Integer> hm = new HashMap<>();

    for (String user : users.split(“,”)) {

    String temp = user.trim();

    if (hm.containsKey(temp))

    hm.put(temp, hm.get(temp) + 1);

    else

    hm.put(temp, 1);

    }

    List<Entry<String, Integer>> list=new ArrayList<>(hm.entrySet());

    Collections.sort(list, new Comparator<Entry<String, Integer>>() {

    @Override

    public int compare(Entry<String, Integer> o1,

    Entry<String, Integer> o2) {

    // TODO Auto-generated method stub

    return o2.getValue()-o1.getValue();

    }

    });

    for(int i=0;i<k;i++)

    {

    Entry<String, Integer> entry=list.get(i);

    System.out.println(entry.getKey()+”(“+entry.getValue()+”)”);

    }

    }}

Log in to reply.

Original Post
0 of 0 posts June 2018
Now
KodNest Training New Batch is starting on 21st September 2020. Attend one week free demo classes.Register Now

New Report

Close