簡體   English   中英

Java將字符串集合減少到出現的映射

[英]Java reduce a collection of string to a map of occurence

將列表視為id1_f, id2_d, id3_f, id1_g ,如何使用流來獲取統計信息的<String, Integer>格式的簡化映射,如:

id1 2
id2 1
id3 1

注意:鍵在_之前是部分。 reduce功能可以幫助嗎?

這將完成工作:

Map<String, Long> map = Stream.of("id1_f", "id2_d", "id3_f", "id1_g")
  .collect(
    Collectors.groupingBy(v -> v.split("_")[0],
    Collectors.counting())
  );

您還可以使用toMap收集器:

myList.stream()
      .collect(Collectors.toMap((String s) -> s.split("_")[0], 
                   (String s) -> 1, Math::addExact);

如果您關心元素的順序,則將結果轉儲到LinkedHashMap

myList.stream()
      .collect(Collectors.toMap((String s) -> s.split("_")[0], 
                   (String s) -> 1, Math::addExact, 
                     LinkedHashMap::new));

使用Map :: merge的非流方法:

Map<String, Integer> result = new LinkedHashMap<>();
myList.forEach(s -> result.merge(s.split("_")[0], 1, Math::addExact));

由於你想要計算元素,我建議使用GuavaMultiset接口,它專門用於此目的。

從JavaDoc中定義Multiset

支持與順序無關的相等的集合,如Set ,但可能具有重復的元素。 multiset有時也被稱為

多重集是彼此相等的元件被稱為相同的單個元件的出現 多集中元素的出現總數稱為該元素的計數

以下是兩種使用方法:

1)沒有Stream API:

ImmutableMultiset<String> multiset2 = ImmutableMultiset.copyOf(Lists.transform(
        list, str -> StringUtils.substringBefore(str, "_")
));

2)使用Stream API:

ImmutableMultiset<String> multiset = list.stream()
        .map(str -> StringUtils.substringBefore(str, "_"))
        .collect(ImmutableMultiset.toImmutableMultiset());

請注意,我沒有使用類似s.split("_")[0] ,而是使用了Apache Commons LangStringUtils.substringBefore ,我發現它更具可讀性。

您可以使用Multiset.count()方法檢索元素的計數。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM