怎么比较两个list中相同的值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了怎么比较两个list中相同的值相关的知识,希望对你有一定的参考价值。
或者得到这两个list中相同值个数!请高手指点一下。谢谢
int count=0;for(int i=0;i<list1.size();i++)
for(int j=0;j<list2.size();j++)
//判断值是否相同
if(list1.get(i).equal(list2.get(j)))
count=count+1;//相同count加一
System.out.println("相同值的个数="+count); 参考技术A import java.util.List;
import java.util.Arrays;
public class EqualList
static String a[]="a","b","c";
static String b[]="c","a","b";
static List list1;
static List list2;
static int count=0;
public static void main(String args[])
list1= Arrays.asList(a);
list2= Arrays.asList(b);
for(int i=0;i<list1.size();i++)
for(int j=0;j<list2.size();j++)
if(list1.get(i).equals(list2.get(j)))
count++;
break;
System.out.println("相同数字的个数"+count);
其实就是加个break的问题,呵呵!
比较两个不同列中相同字段的值
我需要将一列中的两个部分并排放在一个表中,具有相同的描述和不同的“外部ID”。这是输入表的样子:
+--+-------+-----------+
|ID|OUTERID|DESCRIPTION|
+--+-------+-----------+
|1 |1 |some desc 1|
+--+-------+-----------+
|2 |1 |some desc 2|
+--+-------+-----------+
|3 |1 |some desc 3|
+--+-------+-----------+
|4 |2 |some desc 2|
+--+-------+-----------+
|5 |2 |some desc 3|
+--+-------+-----------+
以下是我要从我的选择中实现的目标:
+-------------+-------------+
|DESCRIPTION_1|DESCRIPTION_2|
+-------------+-------------+
|some desc 1 |NULL |
+-------------+-------------+
|some desc 2 |some desc 2 |
+-------------+-------------+
|some desc 3 |some desc 3 |
+-------------+-------------+
我尝试使用简单的JOIN,但正如您所看到的,我需要显示不匹配的值。
SELECT a.DESCRIPTION AS DESCRIPTION_1,
b.DESCRIPTION AS DESCRIPTION_2
FROM My_Table a
JOIN My_Table b on a.DESCRIPTION = b.DESCRIPTION
WHERE a.OUTERID = 1
AND b.OUTERID = 2
答案
如果我理解正确,您可以使用完整的外部联接:
SELECT a.DESCRIPTION AS DESCRIPTION_1,
b.DESCRIPTION AS DESCRIPTION_2
FROM (SELECT a.*
FROM My_Table a
WHERE a.OUTERID = 1
) a FULL JOIN
(SELECT b.*
FROM My_Table b
WHERE b.OUTERID = 2
) b
ON a.DESCRIPTION = b.DESCRIPTION;
另一答案
你需要dense_rank()
并做条件聚合:
select max(case when OUTERID = 1 then DESCRIPTION end) as DESCRIPTION_1,
max(case when OUTERID = 2 then DESCRIPTION end) as DESCRIPTION_2
from (select t.*,
dense_rank() over (order by DESCRIPTION) as seq
from table t
) t
group by seq;
另一答案
使用cte :(虽然,我不知道为什么你需要提供两个列而不是仅仅识别'dupes')
表:
Create Table #tbl
(
ID Int,
OUTERID Int,
DESCRIPTION VarChar(20)
)
Insert Into #tbl Values
(1,1,'some desc 1'),
(2,1,'some desc 2'),
(3,1,'some desc 3'),
(4,2,'some desc 2'),
(5,2,'some desc 3')
CTE
With cte As
(
Select Description, Count(Distinct OuterID) As recs From #tbl
Group By Description
)
Select
Case When recs = 2 Or recs = 1 Then Description End As Description_1,
Case When recs = 2 Then Description End As Description_2
From cte
以上是关于怎么比较两个list中相同的值的主要内容,如果未能解决你的问题,请参考以下文章