【问题标题】:return the list with strings with single occurrence [closed]返回带有单次出现的字符串的列表[关闭]
【发布时间】:2018-01-17 07:37:37
【问题描述】:

给定字符串列表,需要使用java(流)返回不重复(单次出现)的字符串列表 我尝试过使用 distinct,但它不会得到单一的准确度

【问题讨论】:

标签: java string list java-8 java-stream


【解决方案1】:

这样的……

List<String> result = Stream.of("A", "A", "BB", "C", "BB", "D")
            .collect(Collectors.groupingBy(
                         Function.identity(), 
                         Collectors.counting()))
            .entrySet()
            .stream()
            .filter(x -> x.getValue() == 1L)
            .map(Entry::getKey).collect(Collectors.toList());

System.out.println(result); // [C, D]

【讨论】:

  • 或者收集到一个可变的HashMap,调用map.values().removeIf(count -&gt; count &gt;1);并使用map.keySet()作为结果(或者使用new ArrayList&lt;&gt;(map.keySet())将它复制到一个列表中)...
  • @Holger 你的大脑以一种神秘的方式运作......很好的建议,谢谢你!
【解决方案2】:

也许只是问题弄错了,但您正在过滤列表中不重复的条目...

所以这可以工作: 考虑一个列表,其中 C# 和 C++ 是唯一不重复的字符串:

List<String> items = Arrays.asList("Java", "Java", "Java", "C++", "C", "C#", "C");

Map<String, Long> result = items.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

System.out.println(result);

Map<String, Long> filter = result.entrySet().stream().filter(x -> x.getValue() == 1)
        .collect(Collectors.toMap(p -> p.getKey(), p -> p.getValue()));
System.out.println(filter);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2016-03-27
    • 2015-08-05
    • 1970-01-01
    • 2019-08-05
    • 2016-10-23
    • 1970-01-01
    相关资源
    最近更新 更多