How to find unique value of a column of a 2D ArrayList in java?

霸气de小男生 提交于 2019-12-05 11:40:16

For your given datastructure;

Map<String, Long> countMapOfColumn = list.stream()
        .filter(innerList -> innerList.size() >= column)
        .map(innerList -> innerList.get(column - 1))
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

where column = 3, will get you a map with {"C", "G"} as keyset, and values will give you the count of each character in the given column. It will also work for non uniform matrices, since it will just skip the rows that has no nth column.

Unique count of any column will the the size of resulting map of collect method; countMapOfColumn.size()

To get individual char counts, use the resulting map with keys as input, for example to get count of C in column = 3, use countMapOfColumn.get("C"), which will return 2

But I'd rather use a Guava's Table, you can directly select any given row or column without any hassle, then it is only, getting nth column, and filter our duplicates.

update

To get the count of rows that start with consecutive list list = {"A", "B"};

List<String> startingList = Arrays.asList("A", "B");
Long count = list.stream()
        .filter(innerList -> innerList.size() >= startingList.size() 
                && innerList.subList(0, startingList.size()).equals(startingList))
        .count();

Your question doesn't compile. Assuming you have defined the list as follows, you can easily find the distinct value in column 3 by using the following. Here we are just mapping the 3rd column (by using index 2) and then applying .distinct() on the resulting stream.

List<List<String>> list = Arrays.asList(Arrays.asList("A", "B", "C"), 
                                        Arrays.asList("E", "F", "G"),
                                        Arrays.asList("A", "B", "C"));

List<String> distinct = list.stream().map(a -> a.get(2))
                            .distinct().collect(Collectors.toList());

When you print out the elements it will output :

C

G

You can use the same logic to find count of 'C' in column 3 using the same logic.

list.stream().map(a -> a.get(2)).filter(i -> i.contains("C")).count();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!