赞
踩
一:三元运算符
条件表达式 ? 取值1 :取值2
三元运算符是if else或者if else if else的简写形式,可以使代码看起来简洁些。
- private String ternary1(int first){
- System.out.println("===============================================================================================================");
- System.out.println("====三元运算符:if else的模式=====");
- System.out.println("====first=1时返回已售; =====");
- System.out.println("====first!=1时返回未售; =====");
- String str=first==1?"已售":"未售";
- System.out.println("first="+first+",返回:"+str);
- return str;
- }
-
- private String ternary2(int first,int second){
- System.out.println("===============================================================================================================");
- System.out.println("====三元运算符:if else if else的模式=====");
- System.out.println("====first=1,且second=1时返回 再售; =====");
- System.out.println("====first=1,且second!=1时返回 已售; =====");
- System.out.println("====其它情况时返回 未售; =====");
- String str=first==1?(second==1?"再售":"已售"):"未售";
- System.out.println("first="+first+",second="+second+",返回:"+str);
- return str;
- }

二:foreach操作 for(集合中元素的类型或者数组中元素的类型 表示元素的变量 : 数组或者集合的变量或者表达式){}
java在jdk1.5中开始支持foreach循环,foreach在一定程度上简化了对数组、集合的遍历。
- Iterator<String> iterator=collection.iterator();
- while(iterator.hasNext()){
- System.out.println("迭代=="+iterator.next());
- }
三:java8中配合lambda表达式的forEach
- collection.forEach(s -> {
- System.out.println(s);
- });
自定义Consumer<T>类进行迭代
- private class MyConsumer implements Consumer<Object>{
-
- @Override
- public void accept(Object o) {
- System.out.println("打印输出(动作执行的参数):" + o);
- }
- }
-
- private void forEach6(){
- System.out.println("============遍历ArrayList java8 foreach方法============================");
- Collection<String> collection=new ArrayList<>(5);
- for (int i = 0; i <5 ; i++) {
- ((ArrayList<String>) collection).add(i,(i+1)+"");
- }
- collection.forEach(new MyConsumer());
- }

对Map集合的遍历如下所示:
- private void forEach7(){
- System.out.println("============遍历HashMap,不能直接遍历Map============================");
- Map<String,String> map=new HashMap<>(5);
- for (int i = 0; i <5 ; i++) {
- map.put(i+"",i+1+"");
- }
- System.out.println("普通方法遍历Map");
- //其实是在遍历Set集合
- for (Map.Entry<String, String> entry : map.entrySet()) {
- System.out.println("key : " + entry.getKey() + " value : " + entry.getValue());
- }
- System.out.println("java8 lambda遍历Map");
- map.forEach((k,v)->{
- System.out.println("key:"+k+",value:"+v);
- });
- }

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。