简体   繁体   中英

How to get unique values with frequency from List<String[]> in Java?

I want to get unique values from a List<String[]> and store them in a new list (or HashMap<String, Integer> where String is the unique value and Integer is its number of occurrences in the List<String[]> . How can I extract the unique values?

You can use Collectors.groupingBy

Map<String, Long> map = abc.stream()
                           .flatMap(Arrays::stream)
                           .collect(Collectors.groupingBy(Function.identity(),
                                       Collectors.counting()));

If you are using Java 8 or above it's pretty easy. (Slight correction using the other answer)

List<String[]> abc = new ArrayList<>();
String[] string1 = {"123", "567"};
String[] string2 = {"123", "456"};
abc.add(string1);
abc.add(string2);

List<String> newList = abc.stream()
        .flatMap(Arrays::stream)
        .distinct()
        .collect(Collectors.toList());

Map<String, Long> hashMap = abc.stream()
            .flatMap(Arrays::stream)
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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