How to convert an ArrayList containing Integers to primitive int array?

If you are using java-8 there’s also another way to do this. int[] arr = list.stream().mapToInt(i -> i).toArray(); What it does is: getting a Stream<Integer> from the list obtaining an IntStream by mapping each element to itself (identity function), unboxing the int value hold by each Integer object (done automatically since Java 5) getting the … Read more

Java: How to read a text file

You can use Files#readAllLines() to get all lines of a text file into a List<String>. for (String line : Files.readAllLines(Paths.get(“/path/to/file.txt”))) { // … } Tutorial: Basic I/O > File I/O > Reading, Writing and Creating text files You can use String#split() to split a String in parts based on a regular expression. for (String part … Read more

Convert list to array in Java [duplicate]

Either: Foo[] array = list.toArray(new Foo[0]); or: Foo[] array = new Foo[list.size()]; list.toArray(array); // fill the array Note that this works only for arrays of reference types. For arrays of primitive types, use the traditional way: List<Integer> list = …; int[] array = new int[list.size()]; for(int i = 0; i < list.size(); i++) array[i] = … Read more

Why do I get an UnsupportedOperationException when trying to remove an element from a List?

Quite a few problems with your code: On Arrays.asList returning a fixed-size list From the API: Arrays.asList: Returns a fixed-size list backed by the specified array. You can’t add to it; you can’t remove from it. You can’t structurally modify the List. Fix Create a LinkedList, which supports faster remove. List<String> list = new LinkedList<String>(Arrays.asList(split)); … Read more