如何在Java中查找2D ArrayList的列的唯一值? [英] How to find unique value of a column of a 2D ArrayList in java?
问题描述
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
public class Delete
{
public static void main(String[] args)
{
List<List<String>> list = new ArrayList<>();
list.add(List.of("A","B","C","R"));
list.add(List.of("E","F","G","F"));
list.add(List.of("A","B","C","D"));
System.out.println(list.stream().distinct().count());
Map<String, Long> countMapOfColumn = list.stream()
.filter(innerList -> innerList.size() >= 3)
.map(innerList -> innerList.get(3 - 1))
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println(countMapOfColumn.keySet());
}
}
我想找出第3列中的唯一元素"C","G"
,并且在第3列中有2
个唯一元素.
I want to find out the unique element of column 3 which are "C","G"
and there are 2
unique element in column 3.
这可以使用loop
完成,但是我不能使用循环.使用Java stream
可能有解决方案.
This can be done using loop
but I can't use loop. Using java stream
there may be a solution.
此外,如何才能一次获得列1,2
中具有"A","B"
的行的计数,并且通常如何获得N
列?
In addition, how can I get count of rows having "A","B"
in column 1,2
at a time and in general for N
columns?
推荐答案
对于给定的数据结构;
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()));
其中column = 3
将为您提供一个以{"C", "G"}
作为键集的映射,而值将为您提供给定列中每个字符的计数.它也将适用于非统一矩阵,因为它只会跳过没有第n列的行.
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.
任何列的唯一计数将成为collect方法的结果图的大小; countMapOfColumn.size()
Unique count of any column will the the size of resulting map of collect method; countMapOfColumn.size()
要获取单个字符计数,请使用键输入的结果映射作为输入,例如要获取column = 3
中C
的计数,请使用countMapOfColumn.get("C")
,这将返回2
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
但是我宁愿使用番石榴的Table
,您可以直接选择任何给定的行或列而没有任何麻烦,然后仅是,获取第n列,并过滤我们的重复项即可.
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.
更新
获取以连续列表list = {"A", "B"}
开始的行数;
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();
这篇关于如何在Java中查找2D ArrayList的列的唯一值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!