gpt4 book ai didi

java - 我的逻辑有什么问题

转载 作者:行者123 更新时间:2023-11-30 08:00:00 24 4
gpt4 key购买 nike

我有一个自定义类的 ArrayList

public class DetailedData
{
String Company;
String Model;
String Category;
String ImageType;
String ImageBuffer1;
String ImageBuffer2;
}

这是我收到的一小部分数据样本,但大部分都遵循相同的模式。

dell, inspiron 15-R, laptop, Header, 9j4AAQSk, null
dell, inspiron 15-R, laptop, Thumbnail, iVBORw0KGg, null
apple, macbook air, laptop, Header, 9j4AAQSk, null
apple, macbook air, laptop, Thumbnail, iVBORw0KGg, null
dell, xps 13, laptop, Header, 9j4AAQSk, null

我想合并这些重复的数据并将其存储在像这样的新列表中

dell, inspiron 15-R, laptop, Header, 9j4AAQSk, iVBORw0KGg
apple, macbook air, laptop, Header, 9j4AAQSk, iVBORw0KGg
dell, xps 13, laptop, Header, 9j4AAQSk, null

但是我没有收到正确的输出

这是我的逻辑

 ArrayList<DetailedData> data=getList();
ArrayList<DetailedData> temp = new ArrayList<>();
for (int i = 0; i < data.size(); i++)
{
DetailedData currentData = data.get(i);
if (temp.size() == 0)
{
temp.add(currentData);
} else
{
for (int j = 0; j < temp.size(); j++)
{
DetailedData tempData = temp.get(j);
if (tempData.Company.equals(currentData.Company))
{
if (tempData.ImageType.equals(currentData.ImageType))
{}
else
{
temp.get(j).ImageBuffer2 = currentData.ImageBuffer1;
}

} else
{
temp.add(currentData);
}
}
}
}

最佳答案

我找到了一个巧妙的方法,使用流:

List<DetailedData> data = getList();

List<DetailedData> temp = data.stream()
.collect(Collectors.groupingBy(DetailedData::getModel))
.values().stream()
.map(DetailedData::merge)
.collect(Collectors.toList());

temp.forEach(System.out::println);

输出:

dell, xps 13, laptop, Header, 9j4AAQSk, null
dell, inspiron 15-R, laptop, Header, 9j4AAQSk, iVBORw0KGg
apple, macbook air, laptop, Header, 9j4AAQSk, iVBORw0KGg

其中 DetailedData::merge 是一种将 DetailedData 列表合并为 1 的方法。例如:

public static DetailedData merge(List<DetailedData> list) {
if(list.isEmpty()) // Not possible after 'groupingBy'.
return null;

if(list.size() == 1)
return list.get(0);

// At least 2 elements:
DetailedData ret = list.get(0);
ret.ImageBuffer2 = list.get(1).ImageBuffer1;
return ret;
}

参见 Full Code

关于java - 我的逻辑有什么问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38851435/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com