使用Java 8在列表中仅查找重复的String属性

Ris*_*edi 10 java java-8 java-stream

我知道下面是查找列表中每个字符串属性的出现的代码,如何仅使用重复项过滤此列表,即出现多于1次.对不起,我是java 8的新手.

Map<String, Long> result = list.stream()
            .collect(Collectors.groupingBy(Function.identity(),
                                              Collectors.counting()));
Run Code Online (Sandbox Code Playgroud)

Ous*_* D. 7

entrySet和创建一个流filter:

List<Map.Entry<String, Long>> result =  list.stream()
                   .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                   .entrySet()
                   .stream()
                   .filter(s -> s.getValue() >= 2)
                   .collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)

或者如果你想维护一张地图,那么:

Map<String, Long> result = stringList().stream()
                .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
                .entrySet()
                .stream()
                .filter(s -> s.getValue() >= 2)
                .collect(toMap(Map.Entry::getKey, Map.Entry::getValue));
Run Code Online (Sandbox Code Playgroud)

另一方面,如果您只想要出现超过或等于2次的个别数字,那么您可以这样做:

List<String> result = list.stream()
                .collect(Collectors.groupingBy(Function.identity(),
                        Collectors.counting()))
                .entrySet()
                .stream()
                .filter(x -> x.getValue() >= 2)
                .map(Map.Entry::getKey)
                .collect(toList());
Run Code Online (Sandbox Code Playgroud)

另一种选择是:

List<String> result = 
         list.stream()
             .filter(x -> list.stream().filter(x::equals).limit(2).count() == 2)
             .distinct()
             .collect(toList());
Run Code Online (Sandbox Code Playgroud)


Hol*_*ger 6

如果你List是可变的,你可以直接删除除第二次出现之外的所有元素:

// example list
List<String> example = new ArrayList<>();
Collections.addAll(example, "foo", "bar", "baz", "bar", "bar", "baz");

// actual operation
Map<String,Integer> temp = new HashMap<>();
example.removeIf(s -> temp.merge(s, 1, Integer::sum)!=2);

// example output
example.forEach(System.out::println);// prints bar baz
Run Code Online (Sandbox Code Playgroud)

上述解决方案仅为每个具有多次出现的字符串保留一个副本,同时删除所有没有重复的字符串.如果要保留所有重复项并只删除那些没有重复项的字符串,则无法先确定重复状态.

// same example input as above

// actual operation
Map<String,Boolean> temp = new HashMap<>();
example.forEach(s -> temp.merge(s, true, (a,b) -> false));
example.removeIf(temp::get);

// example output
example.forEach(System.out::println);// prints bar baz bar bar baz
Run Code Online (Sandbox Code Playgroud)

在这里,可以使用具有相同逻辑的Stream操作创建临时映射:

Map<String,Boolean> temp = example.stream()
    .collect(Collectors.toMap(Function.identity(), s -> true, (a,b) -> false));
example.removeIf(temp::get);
Run Code Online (Sandbox Code Playgroud)