Search in sources :

Example 51 with Month

use of java.time.Month in project algorithms by Iurii-Dziuban.

the class Main method main.

public static void main(String[] args) {
    // Optional
    // Optional.of(null); // Null pointer
    Optional<Integer> emptyOptional = Optional.empty();
    Optional<Integer> nullableOptional = Optional.ofNullable(null);
    Optional<Integer> fiveOptional = Optional.ofNullable(5);
    System.out.println("Nullable.equals.Empty = " + emptyOptional.equals(nullableOptional));
    System.out.println("emptyOrElse = " + emptyOptional.orElse(5));
    System.out.println("fiveOptional = " + fiveOptional);
    System.out.println("fiveOptionalGet = " + fiveOptional.get());
    System.out.println("fiveOptionalGet = " + fiveOptional.orElse(6));
    System.out.println("fiveOptionalGet = " + fiveOptional.orElseGet(() -> 7));
    // --------------- Exception handling -----------------
    try {
        String s = null;
        // this will be thrown
        s.length();
    } catch (NullPointerException e) {
    } finally {
        try {
            // int i = Integer.parseInt(args[0]); // ArrayIndexOutOfBoundsException
            // ArrayIndexOutOfBoundsException
            int k = Integer.parseInt("1ee");
        } catch (NumberFormatException e) {
            // 
            System.out.println("NumberFormatException");
        } finally {
            System.out.println("Finally");
        }
    }
    // -------------- Data structures ---------------------------
    List<Integer> intArr = new ArrayList<Integer>();
    intArr.add(1);
    intArr.add(2);
    intArr.add(3);
    intArr.add(4);
    intArr.removeIf(e -> e % 2 == 0);
    System.out.println(intArr);
    // only TreeSet has pollFirst and ceiling
    TreeSet treeSet = new TreeSet();
    treeSet.add("A");
    treeSet.add("D");
    // no poll method
    treeSet.pollFirst();
    System.out.println(treeSet.ceiling("D"));
    Map<Integer, String> map = new TreeMap<>();
    map.put(1, "One");
    map.put(2, "Two");
    map.put(3, "Three");
    // replace if key and value to value. But value is different - no replace
    map.replace(1, "1", null);
    // null is a valid value
    map.replace(3, null);
    // map.putIfAbsent(null, null); // null if not supported by default. Only if comparator supports
    System.out.println(map.keySet());
    System.out.println(map.values());
    System.out.println(Arrays.asList("Fred", "Jim", "Sheila").stream().peek(System.out::println).allMatch(s -> s.startsWith("F")));
    Map map1 = new HashMap();
    map1.put("One", 1);
    map1.put("Two", 2);
    map1.put("Three", 3);
    map1.put("Four", 4);
    System.out.println(new TreeMap(map1).ceilingKey("O"));
    ArrayDeque ad = new ArrayDeque();
    ad.add(6);
    ad.add(2);
    ad.offerLast(3);
    ad.offer(4);
    ad.poll();
    System.out.println(ad);
    // -------------- Functional programming --------------------
    // unary operator composition
    LongUnaryOperator longUnaryOperator2x = x -> 2 * x;
    LongUnaryOperator longUnaryOperator1PlusX = x -> 1 + x;
    System.out.println(longUnaryOperator2x.compose(longUnaryOperator1PlusX).andThen(longUnaryOperator1PlusX).applyAsLong(5));
    // stream
    Stream<String> stream = Stream.of("Cat", "Dog", "Rat");
    System.out.println(stream.flatMap(st -> Stream.of(st.length())).collect(Collectors.toSet()));
    // ranges inclusive, exclusive
    IntStream.range(0, 9).forEach(System.out::print);
    System.out.println();
    IntStream.rangeClosed(0, 9).forEach(System.out::print);
    System.out.println();
    // comparator
    Comparator<Name> stringComparator = Comparator.comparing(Name::getName);
    System.out.println(stringComparator.compare(new Name("Aaa"), new Name("Bccc")));
    Comparator<Integer> integerComparator = Integer::compare;
    System.out.println(integerComparator.compare(3, 2));
    Comparable<String> compString = s -> s.hashCode();
    // zero is printed
    Stream.of(3, 6, 0, 4).sorted().peek(System.out::print).findFirst();
    Stream ints = Stream.of(1, 2, 3);
    // long value!!
    long count = ints.skip(1).limit(1).count();
    System.out.println("Count = " + count);
    String[] s = new String[2];
    // System.out.println(Optional.of(s[1]).orElse("empty")); // Null pointer -> use Optional.ofNullable
    System.out.println("Null Last = " + Comparator.nullsLast(Integer::compare).compare(null, 10));
    // --------------- Localization -----------------
    System.out.println(DateFormat.getDateInstance(DateFormat.LONG, new Locale("fr")).format(new Date()));
    Locale localeBuilder = new Locale.Builder().setLanguage("en").setRegion("US").build();
    // "anglais" in English language
    System.out.println(localeBuilder.getDisplayLanguage(new Locale("fr")));
    // -------------- Date Time API ----------------------
    // use of Local time api
    System.out.println(LocalTime.ofSecondOfDay(36000));
    System.out.println(LocalTime.ofSecondOfDay(36000).atOffset(ZoneOffset.UTC));
    // use offset time
    System.out.println(OffsetTime.now());
    // use of period
    System.out.println(LocalDate.parse("2016-01-26").plus(PERIOD_DAYS));
    System.out.println(LocalDate.parse("2010-01-21").plus(PERIOD_DAYS).plus(PERIOD_DAYS));
    // compare two dates. not equal because of leap year
    System.out.println(LocalDate.of(2012, 12, 31));
    System.out.println(LocalDate.ofYearDay(2012, 365));
    // 
    LocalDate date1 = LocalDate.of(2016, Month.JANUARY, 1);
    LocalDateTime date2 = LocalDateTime.of(2017, Month.JUNE, 1, 1, 1);
    // Period p = Period.between(date2, date2); between localDates only!
    Period periodYMD = Period.of(1, 2, 1);
    LocalDate loc = LocalDate.of(2015, 1, 1);
    System.out.println(loc.plusDays(periodYMD.getDays()));
    // month, day of month
    MonthDay.of(10, 28);
    LocalDate loc1 = LocalDate.of(2015, 1, 27);
    LocalDate loc2 = LocalDate.of(2015, 1, 31);
    // System.out.println(Duration.between(loc1, loc2)); unsupported
    System.out.println(LocalDate.parse("2014-05-04").format(DateTimeFormatter.ISO_DATE));
    // .format(DateTimeFormatter.ISO_DATE_TIME));
    // java.time.temporal.UnsupportedTemporalTypeException: Unsupported field: HourOfDay
    // ------------------ IO Streams ------------------------------
    // console
    Console console = System.console();
    // input stream to read specific amount
    try (InputStream inputStream = new ByteArrayInputStream("abcdefghigklmn".getBytes(StandardCharsets.UTF_8.name()))) {
        byte[] buffer = new byte[10];
        int read = inputStream.read(buffer);
        System.out.println(read);
        for (byte c : buffer) {
            System.out.print((char) c);
        }
        System.out.println();
    } catch (IOException e) {
        e.printStackTrace();
    }
    // get owner
    Path path = Paths.get(".");
    try {
        BasicFileAttributes basicFileAttributes = Files.readAttributes(path, BasicFileAttributes.class);
        System.out.println(basicFileAttributes.size() + " " + basicFileAttributes.creationTime() + " " + basicFileAttributes.fileKey() + " " + basicFileAttributes.isDirectory() + " " + basicFileAttributes.isOther() + " " + basicFileAttributes.isRegularFile() + " " + basicFileAttributes.isSymbolicLink() + " " + basicFileAttributes.lastAccessTime() + " " + // no method getOwner
        basicFileAttributes.lastModifiedTime());
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        // works!
        System.out.println(Files.getOwner(path));
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        Map mp = Files.readAttributes(path, "*");
        // no owner
        System.out.println(mp);
    } catch (IOException e) {
        e.printStackTrace();
    }
    /*try {
            List<String> strings = Files.readAllLines(Paths.get("input.txt")); // not a stream
        } catch (IOException e) {
            e.printStackTrace(); // no such file exception
        }*/
    /*FileReader fr = new FileReader("new.txt"); // content ABCD
        System.out.println(fr.read()); // reads first character A to int 65
        fr.close();*/
    Path p1 = Paths.get("in\\new");
    Path p2 = Paths.get("file.txt");
    System.out.println(p1.resolve(p2));
    // ------------- Concurrency ----------------
    // atomic
    AtomicInteger atomicInteger = new AtomicInteger(10);
    System.out.println(atomicInteger.decrementAndGet());
    // executor with callable, runnable, future
    ExecutorService executorService = Executors.newFixedThreadPool(2);
    try {
        // executor service - may submit in the same thread thread.start - always new Thread
        Runnable runnable1 = () -> System.out.println("Runnable");
        Future<?> runnable = executorService.submit(runnable1);
        Callable<Integer> callable1 = () -> {
            System.out.println("Callable");
            return 1;
        };
        Future<Integer> callable = executorService.submit(callable1);
        // only runnable !
        executorService.execute(runnable1);
    } finally {
        executorService.shutdown();
    }
    // ----------------- interfaces, classes, etc. ------
    Equals.someMethod1();
    EqualsImpl.someMethod1();
    new EqualsImpl().someMethod();
    try (MyResource1 r1 = new MyResource1();
        MyResource2 r2 = new MyResource2()) {
        System.out.print("try ");
    } catch (Exception e) {
        // first is thrown others in the resource close are suppressed
        System.out.print("catch ");
        for (Throwable t : e.getSuppressed()) {
            System.out.println(t.getClass().getName());
        }
    }
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) Date(java.util.Date) LocalDateTime(java.time.LocalDateTime) HashMap(java.util.HashMap) Callable(java.util.concurrent.Callable) TreeSet(java.util.TreeSet) ArrayList(java.util.ArrayList) Future(java.util.concurrent.Future) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Locale(java.util.Locale) Map(java.util.Map) LocalTime(java.time.LocalTime) Console(java.io.Console) ZoneOffset(java.time.ZoneOffset) Path(java.nio.file.Path) DateFormat(java.text.DateFormat) ExecutorService(java.util.concurrent.ExecutorService) OffsetTime(java.time.OffsetTime) Period(java.time.Period) Files(java.nio.file.Files) Month(java.time.Month) MonthDay(java.time.MonthDay) IOException(java.io.IOException) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) Executors(java.util.concurrent.Executors) List(java.util.List) Stream(java.util.stream.Stream) TreeMap(java.util.TreeMap) Paths(java.nio.file.Paths) LongUnaryOperator(java.util.function.LongUnaryOperator) Closeable(java.io.Closeable) LocalDate(java.time.LocalDate) DateTimeFormatter(java.time.format.DateTimeFormatter) Optional(java.util.Optional) ArrayDeque(java.util.ArrayDeque) Comparator(java.util.Comparator) InputStream(java.io.InputStream) Locale(java.util.Locale) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) LocalDate(java.time.LocalDate) TreeSet(java.util.TreeSet) IntStream(java.util.stream.IntStream) ByteArrayInputStream(java.io.ByteArrayInputStream) Stream(java.util.stream.Stream) InputStream(java.io.InputStream) BasicFileAttributes(java.nio.file.attribute.BasicFileAttributes) Period(java.time.Period) ByteArrayInputStream(java.io.ByteArrayInputStream) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) HashMap(java.util.HashMap) Map(java.util.Map) TreeMap(java.util.TreeMap) LocalDateTime(java.time.LocalDateTime) Console(java.io.Console) Path(java.nio.file.Path) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) IOException(java.io.IOException) TreeMap(java.util.TreeMap) ArrayDeque(java.util.ArrayDeque) Date(java.util.Date) LocalDate(java.time.LocalDate) IOException(java.io.IOException) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) LongUnaryOperator(java.util.function.LongUnaryOperator) ExecutorService(java.util.concurrent.ExecutorService)

Example 52 with Month

use of java.time.Month in project Bytecoder by mirkosertic.

the class ZoneOffsetTransitionRule method readExternal.

/**
 * Reads the state from the stream.
 *
 * @param in  the input stream, not null
 * @return the created object, not null
 * @throws IOException if an error occurs
 */
static ZoneOffsetTransitionRule readExternal(DataInput in) throws IOException {
    int data = in.readInt();
    Month month = Month.of(data >>> 28);
    int dom = ((data & (63 << 22)) >>> 22) - 32;
    int dowByte = (data & (7 << 19)) >>> 19;
    DayOfWeek dow = dowByte == 0 ? null : DayOfWeek.of(dowByte);
    int timeByte = (data & (31 << 14)) >>> 14;
    TimeDefinition defn = TimeDefinition.values()[(data & (3 << 12)) >>> 12];
    int stdByte = (data & (255 << 4)) >>> 4;
    int beforeByte = (data & (3 << 2)) >>> 2;
    int afterByte = (data & 3);
    LocalTime time = (timeByte == 31 ? LocalTime.ofSecondOfDay(in.readInt()) : LocalTime.of(timeByte % 24, 0));
    ZoneOffset std = (stdByte == 255 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds((stdByte - 128) * 900));
    ZoneOffset before = (beforeByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + beforeByte * 1800));
    ZoneOffset after = (afterByte == 3 ? ZoneOffset.ofTotalSeconds(in.readInt()) : ZoneOffset.ofTotalSeconds(std.getTotalSeconds() + afterByte * 1800));
    return ZoneOffsetTransitionRule.of(month, dom, dow, time, timeByte == 24, defn, std, before, after);
}
Also used : Month(java.time.Month) DayOfWeek(java.time.DayOfWeek) LocalTime(java.time.LocalTime) ZoneOffset(java.time.ZoneOffset)

Example 53 with Month

use of java.time.Month in project mockneat by nomemory.

the class GenerateMonths method main.

public static void main(String[] args) {
    MockNeat mock = MockNeat.threadLocal();
    Month m = mock.months().val();
    System.out.println(m);
    Month summer = mock.months().rangeClosed(JUNE, AUGUST).val();
    System.out.println(summer);
    Month beforeSummer = mock.months().before(JUNE).val();
    System.out.println(beforeSummer);
    String month = mock.months().before(JULY).display(TextStyle.FULL, Locale.CANADA).val();
    System.out.println(month);
}
Also used : Month(java.time.Month) MockNeat(net.andreinc.mockneat.MockNeat)

Example 54 with Month

use of java.time.Month in project mockneat by nomemory.

the class MonthsTest method testDaysInRange.

@Test
public void testDaysInRange() throws Exception {
    Month lower = OCTOBER;
    Month upper = DECEMBER;
    Set<Month> monthSet = EnumSet.of(OCTOBER, NOVEMBER);
    loop(DAYS_CYCLES, MOCKS, r -> r.months().range(lower, upper).val(), m -> assertTrue(monthSet.contains(m)));
}
Also used : Month(java.time.Month) Test(org.junit.Test)

Example 55 with Month

use of java.time.Month in project cuba by cuba-platform.

the class CalendarLoader method loadMonthNames.

protected void loadMonthNames(Calendar resultComponent, Element element) {
    Element monthNames = element.element("monthNames");
    if (monthNames == null) {
        return;
    }
    Map<Month, String> monthNamesMap = new HashMap<>();
    for (Element monthName : monthNames.elements("month")) {
        String monthKey = monthName.attributeValue("month");
        Month monthOfYear = null;
        if (StringUtils.isNotEmpty(monthKey)) {
            monthOfYear = Month.valueOf(monthKey);
        }
        String monthValue = monthName.attributeValue("value");
        if (StringUtils.isNotEmpty(monthValue)) {
            if (monthOfYear != null) {
                monthValue = loadResourceString(monthValue);
                monthNamesMap.put(monthOfYear, monthValue);
            }
        }
    }
    resultComponent.setMonthNames(monthNamesMap);
}
Also used : Month(java.time.Month) HashMap(java.util.HashMap) Element(org.dom4j.Element)

Aggregations

Month (java.time.Month)68 LocalDate (java.time.LocalDate)40 Test (org.junit.Test)30 Test (org.testng.annotations.Test)20 DayOfWeek (java.time.DayOfWeek)17 LocalDateTime (java.time.LocalDateTime)8 LocalTime (java.time.LocalTime)5 ZoneOffset (java.time.ZoneOffset)5 HashMap (java.util.HashMap)5 DateTimeFormatter (java.time.format.DateTimeFormatter)4 YearMonth (java.time.YearMonth)3 Date (java.util.Date)3 List (java.util.List)3 ArrayList (java.util.ArrayList)2 DateTimeRule (android.icu.util.DateTimeRule)1 UseLocalDateTime (com.baeldung.datetime.UseLocalDateTime)1 EnchantmentEventListener (com.lilithsthrone.controller.eventListeners.EnchantmentEventListener)1 InventorySelectedItemEventListener (com.lilithsthrone.controller.eventListeners.InventorySelectedItemEventListener)1 InventoryTooltipEventListener (com.lilithsthrone.controller.eventListeners.InventoryTooltipEventListener)1 SetContentEventListener (com.lilithsthrone.controller.eventListeners.SetContentEventListener)1