java lists.transform_Lists.transform的使用

//transform 实现: List numList = Lists.transform(mapList, s -> Integer.valueOf(s.get("valueItem") + ""));

//还原:List> mapList =Lists.newArrayList();

Map map1 =Maps.newHashMap();

map1.put("nameItem", "香蕉");

map1.put("valueItem", 2);

mapList.add(map1);

Map map2 =Maps.newHashMap();

map2.put("nameItem", "香蕉");

map2.put("valueItem", 3);

mapList.add(map2);

Set set = new HashSet<>();

List value1 =mapList.stream()

.map(o->{

Optional option =o.entrySet().stream()

.findAny()//.findAny()获得是Optional,然后对Optional调用map方法获得的是Optional,而Optional里面的值为null,再调用orElse方法却不会出现问题

.filter(m -> m.getKey().equals("valueItem"))

.map(i->{

Object value2=i.getValue();returnvalue2;

})//.orElse("")//亦可以用orElse

;

option.ifPresent(r-> set.add(Integer.valueOf(r + "")));//存在则直接调用

returnoption.get();

}).collect(Collectors.toList());

System.out.println("-1->" + set); //2,3

System.out.println("-1->" +value1);

}

转自:https://blog.csdn.net/weixin_42201566/article/details/81513769

Lists.transform:能够轻松的从一种类型的list转换为另一种类型的list。

使用场景:

1、把一个List> 中的  所有map对应某个key的value值取出来 返回一个新的list

Map map =Maps.newHashMap();

map.put("1","test1");

map.put("2","test2");

Map map2 =Maps.newHashMap();

map2.put("1","test3");

map2.put("4","test2");

List> list2=Lists.newArrayList();

list2.add(map);

list2.add(map2);

List list3=Lists.transform(list2,s->s.get("1"));

list3.forEach(s-> System.out.println(s));

2、通常可以使用Lists.transform把对象list中的某个属性取出来  返回一个新的list:如下代码

public static voidmain(String[] args) {

List resultList=Lists.newArrayList(new Result(1,"test1"),new Result(2,"test2"),new Result(3,"test3"));//将一个list转化为另外一个list

List nameList=Lists.transform(resultList,tuple ->tuple.getNameStr());

nameList.forEach(s->System.out.println(s));

System.out.println("============");

resultList.forEach(result->{

result.setNameStr("reset");

});

nameList.forEach(s->System.out.println(s));

}classResult{privateInteger id;privateString nameStr;publicResult(Integer id, String nameStr) {this.id =id;this.nameStr =nameStr;

}publicInteger getId() {returnid;

}public voidsetId(Integer id) {this.id =id;

}publicString getNameStr() {returnnameStr;

}public voidsetNameStr(String nameStr) {this.nameStr =nameStr;

}

}

结果:

test1

test2

test3

============

reset

reset

reset

结论:

当Lists.transform()处理的list的值发生改变,那么Lists.transform()处理的结果也会发生改变

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是修改后的代码: ``` from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score, roc_curve from sklearn.model_selection import StratifiedKFold import numpy as np import matplotlib.pyplot as plt # define function to get gcForest configuration def get_config(): config = {} config["random_state"] = 0 config["num_classes"] = 3 config["num_estimators"] = [10, 10, 10] config["criterion"] = ["gini", "gini", "gini"] config["max_depth"] = [None, None, None] config["min_samples_split"] = [2, 2, 2] config["min_samples_leaf"] = [1, 1, 1] config["max_features"] = ["auto", "auto", "auto"] config["max_leaf_nodes"] = [None, None, None] return config # define function to plot ROC curve def plot_roc_curve(fpr, tpr): plt.plot(fpr, tpr, color='darkorange', lw=2, label='ROC curve') plt.plot([0, 1], [0, 1], color='navy', lw=2, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic') plt.legend(loc="lower right") plt.show() # define function to train and evaluate gcForest def train_and_evaluate(X_train, y_train, X_test, y_test): # train gcForest config = get_config() tree = gcForest(config) tree.fit(X_train, y_train) # evaluate gcForest y_pred = tree.predict(X_test) report = classification_report(y_test, y_pred) matrix = confusion_matrix(y_test, y_pred) auc = roc_auc_score(y_test, y_pred, multi_class='ovr') fpr, tpr, _ = roc_curve(y_test, y_pred, pos_label=None) return report, matrix, auc, fpr, tpr # load data x = ... y = ... # scale data min_max_scaler = MinMaxScaler() x = min_max_scaler.fit_transform(x) # define k-fold cross-validation kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=0) # initialize lists to store results reports = [] matrices = [] aucs = [] fprs = [] tprs = [] # loop over folds for train_id, test_id in kfold.split(x, y): X_train, X_test = x[train_id], x[test_id] y_train, y_test = y[train_id], y[test_id] report, matrix, auc, fpr, tpr = train_and_evaluate(X_train, y_train, X_test, y_test) reports.append(report) matrices.append(matrix) aucs.append(auc) fprs.append(fpr) tprs.append(tpr) # calculate average results average_report = np.mean(np.array(reports), axis=0) average_matrix = np.mean(np.array(matrices), axis=0) average_auc = np.mean(np.array(aucs)) mean_fpr = np.mean(fprs, axis=0) mean_tpr = np.mean(tprs, axis=0) # print average results print("Average classification report: \n", average_report) print("Average confusion matrix: \n", average_matrix) print("Average AUC: ", average_auc) # plot average ROC curve plot_roc_curve(mean_fpr, mean_tpr) ``` 注意:需要将数据集x和y替换为实际的数据集,并且需要安装matplotlib库才能成功绘制ROC曲线。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值