How do I print the contents of a List that contains a primitive type int object in it? Prefer answers to print this in one line. This is the code I have.
public static void main(String[] args) {
List<int[]> outputList = new ArrayList<>();
int[] result = new int[] { 0, 1 };
int[] result2 = new int[] { 2, 3 };
outputList.add(result);
outputList.add(result2);
System.out.println(Arrays.toString(outputList.get(0)));
}
This will give me [0,1] but I am looking for {[0,1],[2,3]}
The following one-liner can meet your requirement:
System.out.println(
Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{").replaceAll("\\](?=$)", "}"));
It uses the positive lookbehind and positive lookahead regex assertions. Note that ^ is used for the start of the text and $ is used for the end of the text. The Arrays.deepToString(outputList.toArray()) gives us the string, [[0, 1], [2, 3]] and this solution replaces [ at the start of this string and ] at the end of this string, with { and } respectively.
In case, you want to remove all whitespace as well, you can chain one more replacement as follows:
System.out.println(Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{")
.replaceAll("\\](?=$)", "}").replace(" ", ""));
Demo:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Main {
public static void main(String args[]) {
List<int[]> outputList = new ArrayList<>();
int[] result = new int[] { 0, 1 };
int[] result2 = new int[] { 2, 3 };
outputList.add(result);
outputList.add(result2);
System.out.println(
Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{").replaceAll("\\](?=$)", "}"));
System.out.println(Arrays.deepToString(outputList.toArray()).replaceAll("(?<=^)\\[", "{")
.replaceAll("\\](?=$)", "}").replace(" ", ""));
}
}
Output:
{[0, 1], [2, 3]}
{[0,1],[2,3]}
ONLINE DEMO
You can do it by using StringBuffer class
public static void main(String[] args) {
List<int[]> outputList = new ArrayList<>();
int[] result = new int[]{0, 1};
int[] result2 = new int[]{2, 3};
outputList.add(result);
outputList.add(result2);
StringBuffer output=new StringBuffer();
for (int[] ints : outputList) output.append(Arrays.toString(ints)).append(",");
output.insert(0,"{");
output.replace(output.capacity()-2,output.capacity()-1,"}");
System.out.println(output);
}
Output:
{[0, 1],[2, 3]}
Solution
This one-liner should do it:
System.out.println(list.stream().map(Arrays::toString)
.collect(Collectors.joining(", ", "{", "}")));
(I have line-wrapped it for readability.)
Non-solutions
Since you want the outer list to be enclosed in { ... } we can't use List::toString in the Stream solution above. Likewise, Arrays::deepToString is going to give us the wrong output.
Obviously, this can be fixed using String::replace, but that strikes me as ugly. It is better to use the correct "enclosers" in the first place. (Or change the requirements!!)
Calling Arrays::toString() on an int[][] produced using List::toArray will give you this:
[[I#2a40cd94, [I#f4168b8]
... which is not even close to correct.
Arrays::toString calls toString on the int[] objects, and array classes do not override the Object::toString implementation.
Arrays::deepToString addresses that aspect of the problem.
Related
I am trying to create a method that will recursively reverse an ArrayList of generics, and am running into issues with the declaration of my reversedList array (see line 4 of code below).
As the code stands, I receive the error:
cannot find symbol Class: E
The only way I have found to stop the error is by declaring reversedList inside the method, but then it will reset every time it recurses.
import java.util.ArrayList;
import java.util.List;
public class ListRecursive<E>{
public static List<E> reversedList= new ArrayList<E>();
public static <E> void reverse(ArrayList<E> inputList){
E firstitem = null;
if (inputList.size() == 0 ) {
return;
}
else {
firstitem = inputList.get(0);
inputList.remove(0);
}
reverse(inputList);
reversedList.add( firstitem );
}
Below is the main method, which creates an ArrayList of commmand line arguments and attempts to reverse it using the method above.
public static void main(String args[]){
ArrayList<String> argList = new ArrayList<>();
ArrayList<Double> numericArgs = new ArrayList<>();
for (String s : args) {
argList.add(s);
try {
numericArgs.add(Double.parseDouble(s));
}
catch (NumberFormatException e) {
System.out.println(e.getMessage() + "is not numeric...skipping");
}
}
System.out.print("Command line arguments before reversal: ");
for (int i=0; i<argList.size(); i++)
System.out.print(argList.get(i)+ " ");
System.out.println();
reverse(argList);
System.out.print("Command line arguments afterreversal: ");
for (int i=0; i<argList.size(); i++)
System.out.print(argList.get(i)+ " ");
System.out.println();
}
Presuming that you.
Wanted to do it recursively
Didn't want to destroy the original list.
And didn't want to allocate the new List external to the method.
You can do the following:
public static <E> List<E> reverse(List<E> inputList) {
List<E> ret = new ArrayList<>();
E o = inputList.remove(0);
if (inputList.size() > 0) {
ret = reverse(inputList);
}
// at this point they will be on the stack in reverse order.
// so add them to the stack in that order.
ret.add(o);
// return the orginal list to its initial state by inserting them at the beginning.
inputList.add(0, o);
return ret;
}
Calling with this.
List<Integer> ints = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5));
System.out.println(reverse(ints));
System.out.println(ints);
Produces this output.
[5, 4, 3, 2, 1]
[1, 2, 3, 4, 5]
A non-recursive solution would be, of course, trivial.
Note: The passed List must support List.remove() and be mutable for this to work. If you declare your list using List.of() or Arrays.asList() you must pass your list as an argument to the ArrayList<>() constructor.
First of all, if it's a utility method, why store the parameter, if not, then why is it static. You also don't need multiple instances, as method parameters in java are pass-by-reference. More importantly, recursive means your list will be limited to your call stack limit.
Try It Online
public static <E> void reverse(List<E> list) {
for (int i=0;i<list.size()/2;i++) {
E temp = list.get(i);
list.set(i, list.get(list.size()-i-1));
list.set(list.size()-i-1, temp);
}
}
I tried to create two lists - odds and evens as follows:
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 5, 8, 13, 21));
List<Integer> odds = new ArrayList<>();
List<Integer> evens = new ArrayList<>();
numbers.stream().forEach(x -> x % 2 == 0 ? evens.add(x) : odds.add(x));
}
But it gave me incompatible types error (bad return type in lambda expression
missing return value)
What is the best way to filter a collection to two new collections?
As the other answers explain why it doesn't compile I would use in your case the partitioningBy collector and fetch the resulting lists:
import static java.util.stream.Collectors.partitioningBy;
...
List<Integer> numbers = Arrays.asList(1, 2, 3, 5, 9, 13, 21);
Map<Boolean, List<Integer>> partition =
numbers.stream().collect(partitioningBy(x -> x % 2 == 0));
List<Integer> odds = partition.get(false);
List<Integer> evens = partition.get(true);
Well, you can make your existing code compile with a trivial modification:
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 5, 8, 13, 21));
List<Integer> odds = new ArrayList<>();
List<Integer> evens = new ArrayList<>();
numbers.stream().forEach(x -> (x % 2 == 0 ? evens : odds).add(x));
}
The conditional ?: operator is an expression, which isn't a valid statement on its own. My modified code changes the use of the conditional operator to just select which list to add to, and then calls add on it - and that method invocation expression is a valid statement.
An alternative would be to collect using Collectors.partitioningBy - although in this particular case that would probably be more confusing code than what you've got.
A ternary operator is not a statement. If you're using a forEach block, you'd need a valid Java statement, or a complete block:
numbers.stream().forEach(x -> {
if (x % 2 == 0 ) {
pairs.add(x);
} else {
ods.add(x);
}
});
So in my program I split the first row of data imported by a csv file into an array. Is there anyway that I can add this array into an array list as the first element? Because once I split the second data into an array by a delimiter I then want to store this array in the same arraylist but in element 2. A bit confusing but to summarize is nested arrays in an arraylist possible?
public static ArrayList<String[]> readCSV(Scanner csv, String delimiter, int minCellsPerRow) {
String line = csv.nextLine();
String[] parts = line.split(delimiter);
List<String> list = new ArrayList<String>();
list.add(parts);
}
you can specify insertion index with list.add()... here is an example:
public static void main(String[] args) {
//setup
ArrayList<String> storage;
storage = new ArrayList<String>(Arrays.asList("4","5","6"));
String[] data = {"1","2","3"};
printMe(storage);
//append
storage.addAll(0, Arrays.asList(data));
printMe(storage);
}
public static void printMe(ArrayList<String> strs) {
System.out.println(Arrays.toString(strs.toArray(new String[0])));
}
yields the console result:
[4, 5, 6]
[1, 2, 3, 4, 5, 6]
would this work in your case?
I have to find a best way to find out that elements which is not presented in the second arraylist.
suppose
Arraylist a,b,
Arraylist a={1,2,3,4,5};
Arraylist b={2,3,4};
So basically what I want is to find out that elements of a which is not present in arraylist b.
So what is the best solutions to do that?
List<Integer> c = new ArrayList<>(a);
c.removeAll(b);
Also consider to use Sets instead of Lists.
here is another approach using java 8 -
a.stream().filter(b::contains).collect(Collectors.toList());
You could use Apache Commons Collections, which has a method explicitly for this purpose:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
List<Integer> b = Arrays.asList(new Integer[] { 2, 3, 4 });
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
The printed result is: [1, 5].
The Apache Commons libs are well tested and commonly used to extend standard Java functionalities. This particular method accepts Iterable as parameters, so you can use any Collection you want. You can also mix different collection types:
public static void main(String[] args) {
List<Integer> a = Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 });
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Collection<Integer> aMinusB = CollectionUtils.subtract(a, b);
System.out.println(aMinusB);
}
The printed result is the same, [1, 5].
Check out the Javadoc here.
For sake of completeness, Google's Guava library does not have this feature:
Collection *subtract*(Collection, Collection)
No equivalent--create an ArrayList containing a and then call remove on it for each element in b.
However, it implements a method called Sets.difference() method, which you could use if you prefer Guava and work with sets:
public static void main(String[] args) {
Set<Integer> a = new HashSet<Integer>(Arrays.asList(new Integer[] { 1, 2, 3, 4, 5 }));
Set<Integer> b = new HashSet<Integer>(Arrays.asList(new Integer[] { 2, 3, 4 }));
Set<Integer> aMinusB = Sets.difference(a, b);
System.out.println(aMinusB);
}
The result is all elements in a that doesn't exist in b (i.e. [1, 5] again). Of course, the order is not determined since it operates on sets.
You can try removeAll:
List<Integer> notPresent = new ArrayList<Integer>(a);
notPresent.removeAll(b);
Use org.apache.commons.collections4.ListUtils
Given
List<Integer> a = Arrays.asList(new Integer[]{ 1,2,3,4,5});
List<Integer> b = Arrays.asList(new Integer[]{0,1,2,3});
Action
List<Integer> c = ListUtils.removeAll(b, a)
Result in List c
4, 5
Please try like this
for (Object o : a) {
if (!b.contains(o)) {
// this is not present
}
}
Loop through one list, then check if each element in other list using contains.
Something like this. If you think there may be duplicates in a you can try another type of Collection, like a Set for notPresent.
List<Integer> notPresent = new ArrayList<Integer>();
for (Integer n : a){
if (!b.contains(n)){
notPresent.add(n);
}
}
Try this:
public static void main(String[] args) {
List<Integer> a = new ArrayList<Integer>();
List<Integer> b = new ArrayList<Integer>();
List<Integer> exclusion = new ArrayList<Integer>();
a.add(1);
a.add(2);
a.add(3);
a.add(4);
b.add(1);
b.add(2);
b.add(3);
b.add(5);
for (Integer x : a) {
if (!b.contains(x)) {
exclusion.add(x);
}
}
for (Integer x : exclusion) {
System.out.println(x);
}
}
Try this...
Use the contains() method of List.
ArrayList<Integer> aList = new ArrayList<Integer>();
for (Integer i : a){
if (!(b.contains(i))){
aList.add(i);
}
else{
continue;
}
}
I need your help in arraylist problem. I have 2 arraylist.
ArrayList<string> a = {"fruit=apple,grape,banana;nut=pistachio,chestnut,walnut,peanut;vegetable=broccoli,carrot,cabbage,tomato"}
Arraylist<String> b = {"1:1:2 2:1:2 2:3:4 3:4:4"}
Ok, array b is represent the food in a. lets say
1:1:2 means apple:nut:carrot ,
2:1:2 means grape:pistachio:carrot,
2:3:4 means grape:walnut:tomato and
3:4:4 means banana:peanut:tomato.
Currently I have no idea at all. Hopefully you guys can help me about the idea how to do this.
Thanks in advance
Well, you currently have several problems which are probably confusing the situation:
There is no such class ArrayList<string>, I guess you mean List<string>
Currently your lists consist of a single element, which is a comma / space delimited string. You probably want something more like this:
List fruit = new List(new string[] {"apple", "grape", "banana" });
List nut = new List(new string[] {"pistachio", "chestnut", "walnut", "peanut" });
List vegetable = new List(new string[] {"broccoli", "carrot", "cabbage", "tomato" });
This gives you a list where each element is a nut, fruit or vegetable respectively.
Also your second list should probably look more like this:
List<int[]> combinations = new List<int[]>(
new int[][]
{
new int[] {1, 1, 2},
new int[] {2, 1, 2},
new int[] {2, 3, 4},
new int[] {3, 4, 4},
});
I.e. conbinations is a list of combinations, where each combination consists of 3 integers - the index of each element in the list. (This is possibly a tad confusing and by no means the only option - ask if this bit isn't clear).
In face as arrays are 0-indexed in c#, in fact you probably want this instead:
List<int[]> combinations = new List<int[]>(
new int[][]
{
new int[] {0, 0, 1},
new int[] {1, 0, 1},
new int[] {1, 2, 3},
new int[] {2, 3, 3},
});
This at least makes your data easier to work with, so the only questions remaining are:
How do you get from what you have to the above? (I'll let you have a go at that yourself).
What is it that you are trying to do?
Try Below code it works as expected let me know it it does not fulfill use case.
public static List<String> fruits = new ArrayList<String>();
public static List<String> nuts = new ArrayList<String>();
public static List<String> vegitables = new ArrayList<String>();
/**
* #param args
* #throws ParseException
* #author Rais.Alam
*/
public static void main(String[] args) throws ParseException
{
fruits.add("apple");
fruits.add("grape");
fruits.add("banana");
nuts.add("pistachio");
nuts.add("chestnut");
nuts.add("walnut");
nuts.add("peanut");
vegitables.add("broccoli");
vegitables.add("carrot");
vegitables.add("cabbage");
vegitables.add("tomato");
System.out.println(getValue("1:1:2"));
System.out.println(getValue("2:1:2"));
System.out.println(getValue("2:3:4"));
System.out.println(getValue("3:4:4"));
}
public static String getValue(String key)
{
String returnString = "";
String[] arr = key.split(":");
returnString += fruits.get(Integer.parseInt(arr[0]) - 1) == null ? "" : fruits.get(Integer.parseInt(arr[0]) - 1) + ":";
returnString += nuts.get(Integer.parseInt(arr[1]) - 1) == null ? "" : nuts.get(Integer.parseInt(arr[1]) - 1) + ":";
returnString += vegitables.get(Integer.parseInt(arr[2]) - 1) == null ? "" : vegitables.get(Integer.parseInt(arr[2]) - 1);
return returnString;
}
After running the program you will get below output
apple:pistachio:carrot
grape:pistachio:carrot
grape:walnut:tomato
banana:peanut:tomato