简体   繁体   English

流使用函数式编程

[英]Stream Usage Functional Programming

As was trying to resolve by Functional programming, however, I am stuck in to use more efficiently.然而,正如函数式编程试图解决的那样,我坚持更有效地使用。 Request if one can check out what can be done in this case.请求是否可以检查在这种情况下可以做什么。

For a given array of transactions, each with an item name,group group all transactions by item name.对于给定的交易数组,每个交易都有一个项目名称,按项目名称对所有交易进行分组。 Return an array of strings where each string contains the item name followed by a space and then the number of transactions.Sort the array descending by transaction count, then ascending alphabetically by item name for items with matching transaction counts.返回一个字符串数组,其中每个字符串包含项目名称,后跟一个空格,然后是交易数量。按交易计数对数组进行降序排序,然后对具有匹配交易计数的项目按项目名称的字母顺序升序。

Example: list = ["bold","not","bold","bold"]示例:list = ["bold","not","bold","bold"]

O/P:开/关:

bold 3粗体 3

not 1不是 1

tried approach till descending, but confused on functional programming usages:尝试方法直到下降,但对函数式编程用法感到困惑:

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);
    }
}

Will be helpful if one can explain how to check in this by using decomposition / functional prog.如果可以解释如何使用分解/功能编来检查这一点,将会有所帮助。 approach.方法。


Update 1: After resolute to clean code, This looks much cleaner if not used by Functional Programming更新 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;
}

First create a map using tx name as the key and it's count as value.首先使用 tx 名称作为键创建一个映射,并将其计为值。 Then use this map to build the structure you need.然后使用此地图构建您需要的结构。 Also notice that, when you use the Map.Entry.comparingByValue() along with another chained operator like reversed or thenComparing , the type inference is not powerful enough to figure the type out for itself, so we are forced to help it providing them explicitly.另请注意,当您将Map.Entry.comparingByValue()与另一个链式运算符(如reversedthenComparing Map.Entry.comparingByValue()一起使用时,类型推断的功能不足以自行确定类型,因此我们被迫帮助它明确地提供它们. This is a reported bug and you may find it here .这是一个已报告的错误,您可以在此处找到它。

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM