자바 8 연습

13704 단어 Java
흐름 처리
package stream;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class ListUtil {

	
	public static List getTenOfNumberList() {
		List list = new ArrayList<>();
		list.add(1);
		list.add(2);
		list.add(3);
		list.add(5);
		list.add(7);
		list.add(4);
		list.add(6);
		list.add(9);
		list.add(8);
		list.add(0);
		
		return list;
		
	}
	
	public static List getRepeatNumberList() {
		List list = Arrays.asList(1, 2, 1, 3, 3, 2, 4);
		return list;
	}
}

package stream;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

import java.util.Comparator;

public class Distinct {
	public static void main(String [] args) {
		List list = ListUtil.getRepeatNumberList();
		list = list.stream()
		.filter((num) -> num % 2 == 0)
		.distinct()
		.collect(toList());
		System.out.println(list);
		//       
		list.stream().limit(1).forEach(System.out :: println);
		//        
		list.stream().skip(1).forEach(System.out :: println);
		
		//     (  )             
		boolean allMatch = list.stream().allMatch((i) -> i % 2 == 0);
		System.out.println(allMatch);
		
		//     (  )              
		boolean anyMath = list.stream().anyMatch((i) -> i % 2 == 0);
		System.out.println(anyMath);
		
		//          ,             ,      
		Optional  oneNum = list.stream().map((x) -> x * x * x ).findFirst();
		//       
		boolean isNull = oneNum.isPresent();
		System.out.println("is not null : " + isNull);
		System.out.println(oneNum.get());
		//     ,             ,            map  flatmap          
		//      list.stream().reduce(0,(a,b) -> a + b)  0                    map reduce
		Integer intValue = list.stream().reduce(0,Integer :: sum);
		System.out.println(intValue);
		//   
		Comparator comparator = (x, y) -> x.compareTo(y);
		list.stream().sorted(comparator.reversed()).forEach(System.out::println);
	}
}

package stream;

import java.util.List;
import static java.util.stream.Collectors.toList;

public class Fillter {
	public static void main(String [] args) {
		List list = ListUtil.getTenOfNumberList();
		list = list.stream()
		.filter((i) -> i > 5)
		.collect(toList());
		System.out.println(list);
	}
}

package stream2;

import java.io.Serializable;

/**
 * 
 * @author ShiXiaoQiang
 *
 */
public class People implements Serializable{
	
	private static final long serialVersionUID = 1L;

	/**
	 *   
	 */
	private int age;
	
	/**
	 *   
	 */
	private String name;
	
	/**
	 *     true    false  
	 */
	private boolean sex;
	
	public People() {
		
	}
	
	public People (String name, int age, boolean sex) {
		this.age = age;
		this.name = name;
		this.sex = sex;
	}
	
	public int getAge() {
		return age;
	}
	public People setAge(int age) {
		this.age = age;
		return this;
	}
	public String getName() {
		return name;
	}
	public People setName(String name) {
		this.name = name;
		return this;
	}
	public boolean isSex() {
		return sex;
	}
	public People setSex(boolean sex) {
		this.sex = sex;
		return this;
	}
	
	

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + age;
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		People other = (People) obj;
		if (age != other.age)
			return false;
		return true;
	}

	@Override
	public String toString() {
		return "People [age=" + age + ", name=" + name + ", sex=" + sex + "]";
	}
}
package lambda;

import com.google.common.collect.Lists;
import org.junit.Before;
import org.junit.Test;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class DemoTest {

    private List peopleList = Lists.newArrayList();

    @Before
    public void before() {
        People people = new People();
        people.setAge(10);
        people.setName("xiaoming");
        People people1 = new People();
        people1.setAge(15);
        people1.setName("xiaowang");
        People people2 = new People();
        people2.setName("xiaowang");
        people2.setAge(14);
        People people3 = new People();
        people3.setAge(11);
        people3.setName("xiaoming");
        peopleList.add(people);
        peopleList.add(people1);
        peopleList.add(people2);
        peopleList.add(people3);
    }

    @Test
    public void test() {
        // mergeFunction   mergeFunction  ,        key         ,       map    
        Map map = peopleList.stream()
                .collect(Collectors.toMap(People :: getName, p -> p, (oldP, newP) -> oldP));

        System.out.println(map);
    }
}

package stream2;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.*;

/**
 * 
 * @author ShiXiaoQiang
 *
 */
public class CollectorDemo {
	public static void main(String[] args) {
		//          
		List peoples = Arrays.asList(new People("  ", 10, true),
				new People("  ", 10, true), new People("  ", 18, true),
				new People("  ", 18, false), new People("  ", 24, true),
				new People("  ", 24, true), new People("  ", 23, false),
				new People("  ", 27, true), new People("   ", 65, false));
		// 1.         
		long count = peoples.stream().collect(Collectors.counting());
		peoples.stream().count();
		peoples.size();
		System.out.println(count + " ");
		// ----------------------------------------------
		
		// 2.              (      /     )
		// 2.1     
		Comparator peopleComparator
				= Comparator.comparingInt(People :: getAge);
		// 2.2   
		Optional pMax = peoples.stream().collect(maxBy(peopleComparator));
		System.out.println(pMax.get());
		Optional pMin = peoples.stream().collect(minBy(peopleComparator));
		System.out.println(pMin);
		//       
		System.out.println(peoples.stream().min(peopleComparator));
		
		// 3.         
		int ageSum = peoples.stream().collect(summingInt(People :: getAge));
		System.out.println("    : " + ageSum);
		//        
		ageSum = peoples.stream().map(People :: getAge).reduce(0, Integer :: sum);
		//      
		ageSum = peoples.stream().collect(reducing(0, People :: getAge, Integer :: sum));
		System.out.println("    : " + ageSum);
		
		//     
		double ageAvg = peoples.stream().collect(averagingInt(People :: getAge));
		System.out.println("    :" + ageAvg);
		
		// 4.      
		//            
		String nameJoin = peoples.stream().map(People :: getName).map((str) -> str.concat(",")).collect(joining());
		nameJoin = peoples.stream().map(People :: getName).collect(joining(","));
		System.out.println(nameJoin.substring(0, nameJoin.lastIndexOf(",")));
		
		// 5.     ,  
		//      
		Map> peopleMap= peoples.stream().collect(groupingBy(People :: isSex));
		System.out.println(peopleMap);
		
		//     ,  ,  
		Map>> pGMap = peoples.stream().collect(
				groupingBy(People :: isSex,
							groupingBy((People p) -> {
												if ( p.getAge() < 30)
												{
													return "young";
												}
												else 
												{
													return "old";
												}
											}
									)
						)
				);
		
			System.out.println(pGMap);
			
			
			//groupingBy                  
			Map peopleMapOfCount = peoples.stream()
					.collect(groupingBy(People :: isSex, counting()));
			System.out.println(peopleMapOfCount);
			
			// 5.1   
			Map> peopleInver = peoples.stream().collect(partitioningBy(People :: isSex));
			System.out.println(peopleInver);
			
	}
}


2. 시간
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.time.temporal.TemporalAdjusters;

public class DurationAndPeriodDemo {
	public static void main(String [] args) {
		LocalDateTime ldtStart = LocalDateTime.of(2018, 1, 1, 1, 1, 1);
		LocalDateTime ldtEnd = LocalDateTime.of(2018, 1, 1, 10, 27, 1);
		Duration duration = Duration.between(ldtStart, ldtEnd);
		System.out.println(duration);
		LocalDate ldStart = LocalDate.of(2017, 12, 31);
		LocalDate ldEnd = LocalDate.of(2018, 1, 1);
		Period period = Period.between(ldStart, ldEnd);
		System.out.println(period);
		LocalDate date = LocalDate.of(2014, 3, 18);
		LocalDate ld = date.with(TemporalAdjusters.lastDayOfMonth());
		System.out.println(ld);
	}
}

import java.time.Instant;

/**
 *           
 * @author Administrator
 *
 */
public class InstantDemo {
	public static void main(String [] args) {
		Instant instant = Instant.ofEpochSecond(3);
		Instant instant1 = Instant.ofEpochSecond(3, 0);
		Instant instant2 = Instant.ofEpochSecond(2, 1_000_000_000);
		Instant instant3 = Instant.ofEpochSecond(4,-1_000_000_000);
		System.out.println(instant);
		System.out.println(instant1);
		System.out.println(instant2);
		System.out.println(instant3);
		
	}
}


public class LambdaDemo {
	public static void main(String [] args) {
		process(() -> System.out.println("hello java8 1"));
		process(() -> System.out.println("hello java8 2"));
		process(() -> System.out.println("hello java8 3"));
		Runnable r = () -> System.out.println("hello java8 4");
		process(r);
	}
	
	public static void process(Runnable r) {
		r.run();
	}
}

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.Month;
import java.time.temporal.ChronoField;
/**
 *   (  )java8  api LocalDate   
 * @author Administrator
 *
 */
public class LocalDateDemo {
	public static void main(String [] args) {
		System.out.println("hello time!!!");
		System.out.println("  2018");
		
		LocalDate localDate = LocalDate.of(2017, 12, 31);
		LocalDate localDateToStr = LocalDate.parse("2017-12-31");
		System.out.println("localDate:" + localDate);
		System.out.println("localDateToStr:" + localDateToStr);
		int year = localDate.getYear();
		Month month = localDate.getMonth();
		int monthVal = localDate.getMonthValue();
		int monthVal2 = month.getValue();
		int dayOfMonth = localDate.getDayOfMonth();
		int dayOfYear = localDate.getDayOfYear();
		DayOfWeek dayOfWeek = localDate.getDayOfWeek();
		/**
		 *      
		 */
		boolean isLeap = localDate.isLeapYear();		
		System.out.println("        :" + dayOfWeek.values().length);
		System.out.println("   :" + year);
		System.out.println("  ,    :" + month);
		System.out.println("  ,    :" + monthVal);
		System.out.println("  ,    :" + monthVal2);
		System.out.println("      :" + dayOfMonth);
		System.out.println("      :" + dayOfYear);
		System.out.println("      :    :" + dayOfWeek);
		System.out.println("     :" + isLeap);
		
		/**
		 *   TemporalField   LocalDate
		 * ChronoField      TemporalField  
		 */
		int yearForTemp = localDate.get(ChronoField.YEAR); 
		int monthForTemp = localDate.get(ChronoField.MONTH_OF_YEAR);
		int day = localDate.get(ChronoField.DAY_OF_MONTH);
		 /**
		  *     long ,              ,   xx
		  */
		long xx = localDate.getLong(ChronoField.DAY_OF_MONTH);
		System.out.println("  TemporalField   :" + yearForTemp);
		System.out.println("  TemporalField   :" + monthForTemp);
		System.out.println("  TemporalField        :" + day);
		System.out.println("xx:" + xx);
		/**
		 *       
		 */
		LocalDate localDateNow = LocalDate.now();
		System.out.println("      :" + localDate);
		
	}
}

import java.time.Clock;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.temporal.ChronoField;

public class LocalTimeDemo {
	public static void main(String [] args) {
		LocalTime localTime = LocalTime.of(23, 59, 59);
		LocalTime localTimeToStr = LocalTime.parse("23:59:59");
		System.out.println("localTime:" + localTime);
		System.out.println("localTimeToStr:" + localTimeToStr);
		
		int hour = localTime.getHour();
		int minute = localTime.getMinute();
		int second = localTime.getSecond();
		
		/**
		 *   TemporalField   LocalDate
		 * ChronoField      TemporalField  
		 */
		int hourToTemp = localTime.get(ChronoField.HOUR_OF_DAY);
		int minuteToTemp = localTime.get(ChronoField.MINUTE_OF_HOUR);
		int secondToTemp = localTime.get(ChronoField.SECOND_OF_MINUTE);
		
		System.out.println(hour + ":" + minute + ":" + second);
		
		System.out.println("-----------------------");
		
		System.out.println(hourToTemp + ":" + minuteToTemp + ":" + secondToTemp);
		
		/**
		 *       ,     00:00:38.444
		 */
		System.out.println(LocalTime.now());
		LocalTime time = LocalTime.now();
		LocalDateTime ldt = time.atDate(LocalDate.now());
		System.out.println("ldt:" + ldt);
	}
}

좋은 웹페이지 즐겨찾기