How to covert LinkedList<LinkedList<Integer>>to int[][] type using stream in Java 8? [duplicate] - java

This question already has an answer here:
How to collect the results of a Stream in a primitive array?
(1 answer)
Closed 7 months ago.
How can I convert a LinkedList<LinkedList<Integer>> to int[][] type?
I have created
LinkedList<LinkedList<Integer>> result = new LinkedList<LinkedList<Integer>>();
I want to convert the result to int[][] type using Java 8 functionality.

First of all, how would one convert a LinkedList<Integer> to an int[] using Streams?
This is done by streaming the values, converting the Stream<Integer> to an IntStream, and using its built-in toArray() method:
LinkedList<Integer> list = something;
int[] array = list.stream().mapToInt(i -> i).toArray()
Now that we can convert the inner list, what do we do about the outer list? We start by streaming it (as a Stream<LinkedList<Integer>>), converting the inner data using the above approach (thus making a Stream<int[]>), and then outputting that as an array:
LinkedList<LinkedList<Integer>> list = something;
int[][] array = list.stream()
.map(l -> l.stream().mapToInt(i -> i).toArray())
.toArray(int[][]::new);

Related

java Failed to convert int array to Set using Collectors.toSet() [duplicate]

This question already has answers here:
Java stream - map and store array of int into Set
(3 answers)
How do I convert a Java 8 IntStream to a List?
(5 answers)
Arrays.asList() not working as it should?
(12 answers)
Closed 2 days ago.
i can't understand basic thing here i have :
int[] arr = {2,5,2,4,6,6,1,5,4};
Set<Integer> orederSet = new HashSet<Integer>(Arrays.stream(arr).collect(Collectors.toSet()));
side note :
also this not working :
Set<Integer> orederSet = new HashSet<Integer>(Arrays.asList(arr));
which gives me compile error :
java: method collect in interface java.util.stream.IntStream cannot be applied to given types;
required: java.util.function.Supplier<R>,java.util.function.ObjIntConsumer<R>,java.util.function.BiConsumer<R,R>
found: java.util.stream.Collector<java.lang.Object,capture#1 of ?,java.util.Set<java.lang.Object>>
reason: cannot infer type-variable(s) R
(actual and formal argument lists differ in length)
I dont understand what is wrong in my code ..
Your arr is an int[]. That means you're calling Arrays#stream(int[]), which returns an IntStream. But none of the primitive stream interfaces1 have a #collect(Collector) method. You have to convert the IntStream into a Stream<Integer>. The easiest way to do that is with the IntStream#boxed() method.
int[] arr = {2, 5, 2, 4, 6, 6, 1, 5, 4};
Set<Integer> set =
Arrays.stream(arr) // IntStream
.boxed() // Stream<Integer>
.collect(Collectors.toSet()); // Set<Integer>
As for why the following doesn't work:
Set<Integer> set = new HashSet<>(Arrays.asList(arr));
That's due to Arrays.asList(arr) returning a List<int[]> rather than a List<Integer>.
Neither primitives nor arrays work especially well with generics. Arrays of primitives are worse. A primitive can at least be auto-boxed to the reference type (and vice versa, i.e., unboxed) when appropriate. But primitive arrays have no such special treatment.
1. The primitive stream interfaces include IntStream, LongStream, and DoubleStream.
Try to convert IntStream:
Set<Integer> orderSet = Arrays.stream(arr).boxed().collect(Collectors.toSet());

I would like to reverse a char array, why it fails when using Arrays.sort(arr, Collections.reverseOrder())? [duplicate]

This question already has answers here:
Sort large arrays of primitive types in descending order
(22 answers)
Closed 1 year ago.
If I reverse a string array, it works fine when using
Arrays.sort(arr, Collections.reverseOrder())
but why it does not work on char Array?
public static void main(String[] args) {
String[] temp = new String[] {"ab","aa","ac"};
Arrays.sort(temp, Collections.reverseOrder());
char[] arr = new char[]{'a','b','c'};
Arrays.sort(arr, Collections.reverseOrder());
}
You have an array of primitives. char is a primitive. Collections.sort() works on collections of objects.
To solve the problem do like this ...
Character[] arr = new Character[]{'a','b','c'};
Arrays.sort(arr, Collections.reverseOrder());
Instead of using a primitive type use its wrapper type, which is an object. Then, everything will work.
Collections.reverseOrder() won´t work on primitive types in java such as char type.
You will need to sort it and then reverse using for loop or put chars into string etc.

Is there a way to accept values directly into List using BufferedReader? [duplicate]

This question already has answers here:
How do I convert a Java 8 IntStream to a List?
(5 answers)
Closed 2 years ago.
For arrays we can use:
int[] arr = Arrays.stream(br.readLine().trim.split("\\s+"))
.maptoInt(Integer::parseInt)
.toArray();
Is there any similar way to initialize List in 1 step?
Use the autoboxing methods and collect into a list instead of calling toAray()
...
.boxed().collect(Collectors.toList());
NB: Your variable would be a list like List<Integer> intList = ...
If you have multiple lines in a file of just ints separate by whitespace you can read
then all into a list as follows:
List<Integer> list = null;
try {
list = Files.lines(Path.of("c:/someFile.txt"))
.flatMap(line -> Arrays.stream(line.trim().split("\\s+")))
.map(Integer::parseInt)
.collect(Collectors.toList());
} catch (IOException ioe) {
ioe.printStackTrace();
}
To read in a single line as in your example, you can do it like this.
List<Integer> list = Arrays.stream(br.readLine().trim().split("\\s+"))
.map(Integer::parseInt)
.collect(Collectors.toList());

Convert Nested List of Integers to a two dimensional array using Streams ( List<List<Integer>> -> int[][] ) [duplicate]

This question already has answers here:
Convert ArrayList into 2D array containing varying lengths of arrays
(8 answers)
Closed 3 years ago.
I searched for similar questions but I found only for the object String which dont apply to this case:
Want to convert List<List<Integer>> list to int[][] array using streams
So far I got this:
int[][] array= list.stream().map(List::toArray)...
I used as a base other similar questions I found. But these use String and can't make it work for Integers->int:
// Example with String 1:
String[][] array = list.stream()
.map(l -> l.stream().toArray(String[]::new))
.toArray(String[][]::new);
// Example with String 2:
final List<List<String>> list = ...;
final String[][] array = list.stream().map(List::toArray).toArray(String[][]::new);
You only need to make a few modifications to the String[][] solution:
List<List<Integer>> lists = ...;
int[][] arrays = lists.stream() // Stream<List<Integer>>
.map(list -> list.stream().mapToInt(i -> i).toArray()) // Stream<int[]>
.toArray(int[][]::new);
The mapToInt(i -> i) is unboxing each Integer (i.e. Integer → int).
See:
Stream#mapToInt(ToIntFunction)
IntStream#toArray()

Can I convert array of integer to List<int> or List<Integer> by Arrays.asList(array)? [duplicate]

This question already has answers here:
Closed 12 years ago.
Possible Duplicates:
Arrays.asList() not working as it should?
How to convert int[] into List<Integer> in Java?
Or must I refactor int[] to Integer[] ?
You can't have List<int>
Arrays.asList(array); will return you List with type T of (passed array)
You can have something like
Integer[] a = new Integer[]{1,2,3};
List<Integer> lst = Arrays.asList(a);
You can do this way
Integer[] a ={1,2,4};
List<Integer> intList = Arrays.asList(a);
System.out.println(intList);
Arrays.asList(array) returns a List-type view on the array. So you can use the List interface to access the values of the wrapped array of java primitives.
Now what happens if we pass an array of java Objects and an array of java primitive values? The method takes a variable number of java objects. A java primitive is not an object. Java could use autoboxing to create wrapper instances, but in this case, it will take the array itself as an java object. So we end up like this:
List<Integer> list1 = Arrays.asList(new Integer[]{1,2,3}));
List<int[]> list2 = Arrays.asList(new int[]{1,2,3}));
The first collection holds the integer values, the second one the int[] array. No autoboxing here.
So if you want to convert an array of java primitives to a List, you can't use Arrays.asList, because it will simply return a List that contains just one item: the array.
If you have a array of Integers then you can use Arrays.asList() to get a List of Integers:
Integer[] inters = new Integer[5];
List<Integer> ints = Arrays.asList(inters);
EDIT :
From the comment below from develman, java 6 has support to return List<> object for same method
OLD ANSWER :
Arrays.asList(array) returns you a java.util.List object.

Categories

Resources