D'Souza氏階:
関数型プログラミングによって解決しようとしたが、私は、より効率的に利用するにはこだわっています。1、この場合には何ができるかチェックすることができるならば、要求。
項目名によるトランザクションの所与のアレイは、項目名と各グループのグループすべてのトランザクションのために。各文字列は空白に続く項目名と、トランザクション数が一致する項目について、項目名のアルファベット順に昇順トランザクション数によってtransactions.Sort配列下降の後、数を、含まれている文字列の配列を返します。
例:リスト= [ "太字"、 "しない"、 "太字"、 "太字"]
O / P:
太字3
ない1
降順までのアプローチを試してみましたが、関数型プログラミングの用途に混乱:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class PYT {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
list.add("bold");
list.add("not");
list.add("bold");
list.add("bold");
System.out.println(grT(list));
}
private static List<String> grT(List<String> list) {
//here this is wrong, as throwing error
Map<Integer, Long> frequencies = ((CharSequence) list).codePoints()
.parallel()
.boxed()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
// sort by descending frequency and collect code points into array
int[] output = frequencies.entrySet()
.parallelStream()
.sorted(Map.Entry.<Integer, Long>comparingByValue().reversed())
.mapToInt(Map.Entry::getKey)
.toArray();
// create output string from List of Strings.
// Could not think of a way to return a list of string --> Error
return new String(output, 0, output.length);
}
}
1は分解/機能PROGを使用して、この中でチェックする方法を説明できるならば参考になります。アプローチ。
アップデート1:関数型プログラミングで使用されていない場合はクリーンなコードに毅然とした後、これは非常にきれいに見えます
private static List<String> ascendingOrder(List<String> list) {
Map<String, Long> stringCount = new HashMap<>();
for (String t : list) {
stringCount.merge(t, 1L, Long::sum);
}
List<Map.Entry<String, Long>> toSort = new ArrayList<>();
for (Map.Entry<String, Long> e : stringCount.entrySet()) {
toSort.add(e);
}
toSort.sort(Map.Entry.<String, Long>comparingByValue().reversed().thenComparing(Map.Entry.comparingByKey()));
List<String> refinedList = new ArrayList<>();
for (Map.Entry<String, Long> e : toSort) {
String s = e.getKey() + " " + e.getValue();
refinedList.add(s);
}
return refinedList;
}
ラビンドラRanwala:
まず、キーと値としての数としてTX名を使用してマップを作成します。次に、必要な構造を構築するために、このマップを使用します。また、あなたが使用することを予告Map.Entry.comparingByValue()
のような他の連鎖演算子と一緒にreversed
かthenComparing
、私たちは、それが明示的に提供するヘルプを余儀なくされているので、型推論は、自分自身のためのタイプを把握するための強力な十分ではありません。これは、報告されたバグであり、あなたはそれを見つけることがここに。
private static final String SPACE = " ";
Map<String, Long> frequencyMap = tx.stream()
.collect(Collectors.groupingBy(t -> t, Collectors.counting()));
List<String> formattedTx = frequencyMap.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue().reversed()
.thenComparing(Map.Entry.comparingByKey()))
.map(e -> e.getKey() + SPACE + e.getValue())
.collect(Collectors.toList());