Wednesday, 25 November 2020

Write a program to print top N trending hashtags

 You are given a set of hashtags and the number of times those have occured. 

Write a java program to print top N trending hashtags from the list of values.

Solution: The best suited data structure for figuring out top N elements is a heap - PriorityQueue is the java implementation for heap.

github: https://github.com/prasune/Algorithms/tree/master/src/main/java/com/test/algorithm/heap

package com.test.algorithm.heap;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.PriorityQueue;

public class TopNHashtags {

public static void main(String[] args) {
int n = 3;
List<HashTagCount> hashTagList = new ArrayList<>();
hashTagList.add(new HashTagCount("#sometag", 10));
hashTagList.add(new HashTagCount("#sometag1", 1000));
hashTagList.add(new HashTagCount("#sometag2", 900));
hashTagList.add(new HashTagCount("#sometag3", 100));
hashTagList.add(new HashTagCount("#sometag4", 50));
hashTagList.add(new HashTagCount("#sometag", 10));

printTopNTrendingHashTags(n, hashTagList);
}

private static void printTopNTrendingHashTags(int n, List<HashTagCount> hashTagList) {
PriorityQueue<HashTagCount> topTrendingHashTags =
new PriorityQueue<>(Comparator.comparing(HashTagCount::getCount).reversed());
topTrendingHashTags.addAll(hashTagList);
for (int i = 0; i< n; i++) {
System.out.println(topTrendingHashTags.poll());
}
}
}


package com.test.algorithm.heap;

import java.util.Objects;

public class HashTagCount {

private String hashTag;

private long count;

public HashTagCount(String hashTag, long count) {
this.hashTag = hashTag;
this.count = count;
}

public String getHashTag() {
return hashTag;
}

public void setHashTag(String hashTag) {
this.hashTag = hashTag;
}

public long getCount() {
return count;
}

public void setCount(long count) {
this.count = count;
}

@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
HashTagCount that = (HashTagCount) o;
return hashTag.equals(that.hashTag);
}

@Override
public int hashCode() {
return Objects.hash(hashTag);
}

@Override
public String toString() {
return "TweetCount{" +
"hashTag='" + hashTag + '\'' +
", count=" + count +
'}';
}
}

No comments:

Post a Comment