您的位置:首页 > 编程语言 > Java开发

Java 8新特性 自己项目中总结

2017-07-19 10:55 197 查看
public class StreamDemo {

public static void main(String[] args) {

List<Transaction> transactions = new ArrayList<Transaction>();
List<Transaction> transactions1 = new ArrayList<Transaction>();
for (int i = 0; i < 10; i++) {
Transaction transaction = new Transaction();
transaction.setId(1+(int)(Math.random()*50)); //产生随机数( 0- 50)
transaction.setValue(1+(int)(Math.random()*50)); //产生随机数( 0- 50)
transactions.add(transaction);
}

//循环取值
transactions.stream().forEach(item ->{
System.out.println(item.getId());
});

//排序
List<Transaction> tranSort = transactions.stream().sorted(Comparator.comparing(Transaction::getValue)).collect(Collectors.toList());
System.out.println(tranSort);
 
//获取数组
List<Integer> tranList = transactions.stream().collect(Collectors.mapping(Transaction::getValue,Collectors.toList()));
Integer[] tranLists = tranList.toArray(new Integer[]{});
System.out.println(tranLists);

//map
Map&
9366
lt;Integer,Integer> maps = transactions.stream().collect(Collectors.toMap(Transaction::getId, Transaction::getValue));
System.out.println(maps);

//去重复
List<Integer> distin = transactions.stream().map(Transaction::getId).distinct().collect(Collectors.toList());
System.out.println(distin);

//移除指定值
transactions1 = transactions.stream().filter(item ->item.getId() != 1).collect(Collectors.toList());
System.out.println(transactions1);

//map key 取值
System.out.println(getMapVal("1"));

// map val --> key
Map<String, String> maps = Maps.newHashMap();
maps.put("2","1");
maps.put("3","1");
System.out.println(listMapVals(maps,"1"));
}

//map key --> val
private static String getMapVal(String key){
Map<String, String> maps = Maps.newHashMap();
maps.put("2","1");
maps.put("3","2");
maps.put("4","3");
maps.put("1","4");
return maps.get(key);
}

// map val --> key
private static List<String> listMapVals(Map<String, String> maps,String value){
List<String> lists = new ArrayList<String>();
for (String getkey : maps.keySet()) {
if(maps.get(getkey).equals(value)){
lists.add(getkey);
}
}
return lists;
};

}

public class Transaction {

private int id;
private int value;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getValue() {
return value;
}
public void setValue(int value) {
this.value = value;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: