import java.util.*;
public class TopN2 {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
Random random = new Random();
for (int i = 0; i < 10; i++) {
int score = random.nextInt(100);
list.add("theme_id" + i + ":" + score);
}
String[] topN = getTopN(list, 3);
myPrint(list, topN);
}
public static String[] getTopN(List<String> list, int N) {
String[] topN = new String[N];
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String value = it.next();
for (int i = 0; i < topN.length; i++) {
if (topN[i] == null) {
topN[i] = value;
break;
} else {
String lastValue = topN[i];
if (Integer.valueOf(value.split(":")[1]) >= Integer.valueOf(lastValue.split(":")[1])) {
for (int j = topN.length - 1; j > i; j--) {
topN[j] = topN[j - 1];
}
topN[i] = value;
break;
}
}
}
}
return topN;
}
public static void myPrint(List<String> list, String[] topN) {
for (int i = 0; i < list.size(); i++) {
System.out.println(list.get(i));
}
System.out.println("-----------------------------");
for (int i = 0; i < topN.length; i++) {
System.out.println(topN[i]);
}
}
}
package udf;
import org.apache.hadoop.hive.ql.exec.UDF;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
public class TopnUDF extends UDF {
public String[] evaluate(String str, String sep1, String sep2, int a, int b) {
String[] topN = new String[b];
try {
if (!str.isEmpty()) {
List<String> list = Arrays.asList(str.split(sep2));
Iterator<String> it = list.iterator();
while (it.hasNext()) {
String value = it.next();
for (int i = 0; i < topN.length; i++) {
if (topN[i] == null) {
topN[i] = value;
break;
} else {
String lastValue = topN[i];
if (Integer.valueOf(value.split(sep1)[a]) >= Integer.valueOf(lastValue.split(sep1)[a])) {
for (int j = topN.length - 1; j > i; j--) {
topN[j] = topN[j - 1];
}
topN[i] = value;
break;
}
}
}
}
}
} catch (Exception e) {
System.out.println(e.toString());
}
return topN;
}
public static void main(String[] args) {
String str = "10001:8:95#10001:9:90#10002:10:85#10003:11:80#10004:11:99";
String[] topn = new TopnUDF().evaluate(str, ":", "#", 2, 3);
for (int i = 0; i < topn.length; i++) {
System.out.println(topn[i]);
}
}
}
参考:https://blog.youkuaiyun.com/zeb_perfect/article/details/53333606