Print unique values from collection using Stream API [duplicate]

我的未来我决定 提交于 2020-05-26 09:26:06

问题


I need to get only unique values from the collection( values which do not have any dublicates in collection). For example, this code:

ArrayList<Integer> g =  new ArrayList<>(Arrays.asList(1,1,2,2,3,4,5,5,5,6,6));
System.out.println(Arrays.toString(g.stream().mapToInt(Integer::intValue).distinct().toArray()));

gives me this result:

[1, 2, 3, 4, 5, 6]

However I want the result:

[3, 4]

Is there any way to do it with Stream API?


回答1:


List<Integer> source = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6);
List<Integer> processed = source.stream()
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
        .entrySet().stream()
        .filter(e -> e.getValue() == 1)
        .map(Map.Entry::getKey)
        .collect(Collectors.toList());
System.out.println(processed);

Result:

[3, 4]



回答2:


You can do it as follows:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

public class Collusion {

    public static void main(String[] args) {
        List<Integer> g = Arrays.asList(1, 1, 2, 2, 3, 4, 5, 5, 5, 6, 6);
        System.out.println(g.stream().filter(x -> Collections.frequency(g, x) < 2).collect(Collectors.toList()));
    }
}

Output:

[3, 4]


来源:https://stackoverflow.com/questions/60605971/print-unique-values-from-collection-using-stream-api

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!