0
私はArrayListの最終リストをマージしたいArrayListの2つのリストを持っています。を比較し、2つのリストをマージして最終的なリストを生成するjavaのリストのリスト
例私は
List<List<String>> data1 = dao1.getall();
List<List<String>> data2 = dao2.getall();
DATA1として、これらのアイテムを取得し、データベース呼び出しを持っていることは
"results": [
[
"India",
"Idea",
"30"
],
[
"USA",
"Idea",
"10"
],
[
"irland",
"Idea",
"10"
]
DATA2の結果セットのように見えますが
"results": [
[
"India",
"Idea",
"50"
],
[
"usa",
"Idea",
"30"
],
[
"sweden",
"Idea",
"10"
]
の結果セットのように見える私は希望CountryとOperatorのフィールドを比較することで、これらの2つのList of Listsを以下のようにマージします。
"results": [
[
"India",
"Idea",
"30",
"50",
"80" ====== sum of the above two values
],
[
"usa",
"Idea",
"10",
"30",
"40"
],
[
"irland",
"Idea",
"10"
"0"
"10"
]
[
"sweden",
"Idea",
"0"
"10" ==== order is very important here
"10"
]
誰でも私にお手伝いできますか?ありがとうございます。
私はこれを試しましたが、私のために働いていませんでした。
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;
Public class Hello{
public static void main(String[] args) {
List<List<String>> list1 = new ArrayList<List<String>>();
List<List<String>> list2 = new ArrayList<List<String>>();
// add data
List<String> datalist1 = new ArrayList<String>();
datalist1.add("India");
datalist1.add("vodafone");
datalist1.add("23");
list1.add(datalist1);
System.out.println(list1);
List<String> datalist2 = new ArrayList<String>();
datalist2.add("India");
datalist2.add("vodafone");
datalist2.add("20");
list2.add(datalist2);
System.out.println(list2);
Collection<List<Country>> list3 = Stream.concat(list1.get(0).stream(), list2.get(0).stream())
.collect(Collectors.toMap(Country::getCountryName, Country::getOperator, Country::merge)).values();
}
private static final class Country {
private final String countryName;
private final String operator;
private final List<String> value;
public Country(String countryName, String name, List<String> values) {
this.countryName = countryName;
this.operator = name;
this.value = values;
}
public String getCountryName() {
return countryName;
}
public String getOperator() {
return operator;
}
public List<String> getValue() {
return value;
}
/*
* This method is accepting both Country and merging data that you need.
*/
public static Country merge(Country country1, Country country2) {
if (country1.getCountryName().equalsIgnoreCase(country2.getCountryName().toLowerCase())
&& country1.getOperator().equalsIgnoreCase(country2.getOperator().toLowerCase())) {
List<String> newValue = country1.getValue();
newValue.add(country2.getValue().get(0));
Integer Total = Integer.parseInt(country1.getValue().get(0)) + Integer.parseInt(country2.getValue().get(0));
newValue.add(Total.toString());
return new Country(country1.getCountryName(), country1.getOperator(), newValue);
}
return new Country(country1.getCountryName(), country1.getOperator(), country1.getValue());
}
}
}
あなたが求めていることを達成するためのコードは既にありますか? – LuisFerrolho