Search in sources :

Example 1 with LongUnaryOperator

use of java.util.function.LongUnaryOperator in project j2objc by google.

the class LongUnaryOperatorTest method testAndThen.

public void testAndThen() throws Exception {
    LongUnaryOperator plusOne = x -> x + 1L;
    LongUnaryOperator twice = x -> 2L * x;
    assertEquals(12, plusOne.andThen(twice).applyAsLong(5L));
}
Also used : LongUnaryOperator(java.util.function.LongUnaryOperator) TestCase(junit.framework.TestCase) LongUnaryOperator(java.util.function.LongUnaryOperator)

Example 2 with LongUnaryOperator

use of java.util.function.LongUnaryOperator in project j2objc by google.

the class LongUnaryOperatorTest method testCompose.

public void testCompose() throws Exception {
    LongUnaryOperator plusOne = x -> x + 1L;
    LongUnaryOperator twice = x -> 2L * x;
    assertEquals(11L, plusOne.compose(twice).applyAsLong(5L));
}
Also used : LongUnaryOperator(java.util.function.LongUnaryOperator) TestCase(junit.framework.TestCase) LongUnaryOperator(java.util.function.LongUnaryOperator)

Example 3 with LongUnaryOperator

use of java.util.function.LongUnaryOperator in project j2objc by google.

the class LongUnaryOperatorTest method testAndThen_null.

public void testAndThen_null() throws Exception {
    LongUnaryOperator plusOne = x -> x + 1L;
    try {
        plusOne.andThen(null);
        fail();
    } catch (NullPointerException expected) {
    }
}
Also used : LongUnaryOperator(java.util.function.LongUnaryOperator) TestCase(junit.framework.TestCase) LongUnaryOperator(java.util.function.LongUnaryOperator)

Example 4 with LongUnaryOperator

use of java.util.function.LongUnaryOperator in project j2objc by google.

the class LongUnaryOperatorTest method testCompose_null.

public void testCompose_null() throws Exception {
    LongUnaryOperator plusOne = x -> x + 1;
    try {
        plusOne.compose(null);
        fail();
    } catch (NullPointerException expected) {
    }
}
Also used : LongUnaryOperator(java.util.function.LongUnaryOperator) TestCase(junit.framework.TestCase) LongUnaryOperator(java.util.function.LongUnaryOperator)

Example 5 with LongUnaryOperator

use of java.util.function.LongUnaryOperator 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)

Aggregations

LongUnaryOperator (java.util.function.LongUnaryOperator)5 TestCase (junit.framework.TestCase)4 ByteArrayInputStream (java.io.ByteArrayInputStream)1 Closeable (java.io.Closeable)1 Console (java.io.Console)1 IOException (java.io.IOException)1 InputStream (java.io.InputStream)1 StandardCharsets (java.nio.charset.StandardCharsets)1 Files (java.nio.file.Files)1 Path (java.nio.file.Path)1 Paths (java.nio.file.Paths)1 BasicFileAttributes (java.nio.file.attribute.BasicFileAttributes)1 DateFormat (java.text.DateFormat)1 LocalDate (java.time.LocalDate)1 LocalDateTime (java.time.LocalDateTime)1 LocalTime (java.time.LocalTime)1 Month (java.time.Month)1 MonthDay (java.time.MonthDay)1 OffsetTime (java.time.OffsetTime)1 Period (java.time.Period)1