I am trying to implement DES code in java. I have bit stream of 64bits that I required to change it to ArrayList of Integer type.
I am able to convert it to an array as shown below.
public class strtoArr {
public static void main(final String[] args)
{
final String string = "0100010111010001000011110111110100010110110011001010001101010010";
final char[] ch=string.toCharArray();
for (final char chh: ch ) {
System.out.print(chh);
}
}
}
I want an Arraylist of integer type so that I can access each element index wise.
Why not just :
String string = "0100010111010001000011110111110100010110110011001010001101010010";
List<Integer> list = new ArrayList<Integer>();
for (int i = 0; i < string.length(); i++) {
list.add(Integer.parseInt(String.valueOf(string.charAt(i))));
}
Here we create a list of type Integer and then iterate over each character of the string and parse it to an int.
Approach using stream API.
Arrays.stream(str.split(“”))
.map(Integer::valueOf)
.collect(toList());
or Pattern API:
Pattern.compile(“”)
.splitAsStream(str)
.map(Integer::valueOf)
.collect(toList());
Related
I am working on the first part of a String permutation problem and I am just looping over the first char of a string and swap it with every following char of that same String. I initialized an empty ArrayList to store all of those permutations called listeFinale. When I am printing that ArrayList, I am getting a collection of object and not values ([[C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba, [C#61bbe9ba]), how can I print each char stored in the ArrayList?
import java.util.ArrayList;
import java.util.List;
public class checkPermu {
public static void main(String[] args) {
String myString = "aabc";
applyPermu(myString);
}
public static void applyPermu(String toCheck){
char[] newString = toCheck.toCharArray();
List listeFinale = new ArrayList();
for(int i = 0 ; i < newString.length ; i ++){
char temp = newString[0];
newString[0] = newString[i];
newString[i] = temp;
listeFinale.add(newString);
System.out.println(listeFinale);
}
}
}
First of all, don't use raw types for your List please.. Change:
List listeFinale = new ArrayList();
to:
List<char[]> listeFinale = new ArrayList<>();
As for your actual problem. Those values you see are the default toString() outputs of your inner character-arrays. You could iterate over your list, and call the java.util.Arrays.toString(char[]) method for them like this:
listeFinale.forEach(arr -> System.out.println(Arrays.toString(arr)));
Or, if you want to print them back as String again, use new String(char[]):
listeFinale.forEach(arr -> System.out.println(new String(arr)));
Try it online.
I have a column VALUE in my table that contains:
`M_SYSCONFIG = 200600,2600000,700000600,110000600,150000600`
When I sort this list the result is:
110000600,150000600,110000600,200600,2600000,700000600
However, I need the list to be sorted as follows (treat the strings as integers):
200600,2600000,110000600,150000600,700000600
This is the code I have right now for sorting the list:
JSONArray jsArray = dbcon.callSelectRecords("SELECT CODE, VALUE FROM M_SYSCONFIG WHERE MODULE = 'LIMIT_CONFIG' AND CODE in (?,?,?,?) ORDER BY VALUE", ft_other_cn, ft_own_account, payment, purchase);
for (int i = 0; i< jsArray.size(); i++) {
JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
String trasactionType = JSON.get(js, "CODE");
String value = JSON.get(js, "VALUE");
List<String> data = Arrays.asList(value.split(","));
Collections.sort(data);
I need to obtain the results as strings because after sorting I want to apply the following code:
StringBuilder sbValue = new StringBuilder();
if(ft_other_cn.equals(trasactionType)) {
long limitOtherCimb = limit.getFtOtherCimbLimit();
sbValue.append(limitOtherCimb).append(",");
for(String values:data) {
Long limitSysConfig = null;
try {
limitSysConfig = Long.parseLong(values);
} catch (Exception e) {}
if(limitSysConfig == null) {
continue;
}
if(limitSysConfig > limitOtherCimb) {
continue;
}
sbValue.append(limitSysConfig).append(",");
}
customerLimit.setFtOtherCnLimit(StringUtils.removeEnd(sbValue.toString(), ","));
You need to convert you string values to integers like this and then need to sort.
JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
String trasactionType = JSON.get(js, "CODE");
String value = JSON.get(js, "VALUE");
List<String> data = Arrays.asList(value.split(","));
List<Integer> intList = new ArrayList<Integer>();
for(String s : data){
intList.add(Integer.valueOf(s));
}
Collections.sort(intList);
I suggest using biginteger because your numbers seems quite large. It's not the most efficient and optimized solution but yeah it will work
public static List<String> sortData(List<String> data){
List<BigInteger>convertedData=new ArrayList<BigInteger>();
for (String s : data)
{
//System.out.println(s);
convertedData.add(new BigInteger(s));
}
Collections.sort(convertedData);
List<String>sortedData=new ArrayList<String>();
for (BigInteger b : convertedData)
{
sortedData.add(String.valueOf(b));
}
return sortedData;
}
Your code:
JSONArray jsArray = dbcon.callSelectRecords("SELECT CODE, VALUE FROM M_SYSCONFIG WHERE MODULE = 'LIMIT_CONFIG' AND CODE in (?,?,?,?) ORDER BY VALUE", ft_other_cn, ft_own_account, payment, purchase);
for (int i = 0; i< jsArray.size(); i++) {
JSONObject js = JSON.newJSONObject(jsArray.get(i).toString());
String trasactionType = JSON.get(js, "CODE");
String value = JSON.get(js, "VALUE");
List<String> data = Arrays.asList(value.split(","));
List<String> sortedData=sortData(data); **<------**
Implement a Comparator like this:
Collections.sort(data, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return new Long(Long.parseLong(o1)).compareTo(Long.parseLong(o2));
}
});
You can take help of streams introduced in java 8.
Just add the below line after creating the List and you would have sorted string list
List<String> data = Arrays.asList(value.split(","));
data=data.stream().mapToLong(Long::parseLong).sorted().mapToObj(String::valueOf).collect(Collectors.toList());
If you very large numbers you can use BigInteger
data=data.stream().map(BigInteger :: new ).sorted().map(String::valueOf).collect(Collectors.toList());
If you are using java 6,7 you would have to use a comparator as mentioned by Taher
Collections.sort(data, new Comparator<String>() {
#Override
public int compare(String o1, String o2) {
return new Long(Long.parseLong(o1)).compareTo(Long.parseLong(o2));
}
});
If you are not able to change your list, then the simplest way is to build a comparator using Java 8 and use the string values as bigintegers. You do not need to convert your string list to a number list.
List<String> list = Arrays.asList("200600,2600000,700000600,110000600,150000600".split(","));
list.sort(Comparator.comparing(item -> new BigInteger(item)));
System.out.println(list);
The magic happens within
Comparator.comparing(item -> new BigInteger(item))
With this you are constructing a Comparator (which is needed for sorting), that compares all items converted to BigIntegers.
You are sorting the numbers as Strings - as a string, 11 comes before 2. You need to first convert the array of strings to numbers, then sort them as numbers.
With the Streams API you can do that on one line:
String value = ...;
List<Long> data = Arrays.stream(value.split(",")).map(Long::new).sorted()
.collect(Collectors.toList());
Since you need them as Long later, I'm using Long as the numeric type.
I try to parse a textfile which has lines which look like the following:
#KEY,_,0,1,2,_,4,5,6, ...
The #KEY is just an identifier in the beginning while the following numbers are my data which I want to store in an ArrayList<Integer>.
I have a metadata class which contains the arraylist in which I want to insert there integers:
class MetaD {
public List<Integer> key1, key2, key3 = new ArrayList<Integer>();
}
I parse the textfile line by line; when the line starts with #KEY, I want to add the elements to the key1 list. If there is an _, it should be replaced with an empty value:
if(line.startsWith("#KEY")){
metaObject.key1 = Arrays.asList(line.replace("#KEY,", "").replace("_", "").trim().split("\\s*,\\s*"));
}
I found out that this does not work with ArrayList<Integer>. key1 has to be of the type ArrayList<String> or ArrayList<Object> to make it work.
Is there a way to convert Integers in the same way?
If not, my idea would be the following:
Convert everything to an ArrayList<String>
Iterate every item of this new ArrayList and convert it with Integer.parseInt() into an Integer.
Adding this new Integer to my ArrayList<Integer>
Would there be a more efficient or better way to archive my needs?
Edit:
Since Tunaki wrote in the comments, that my idea will probably be the only possible way I tried to do the following:
if(line.startsWith("#KEY")){
List<String> channelTemp = Arrays.asList(line.replace("#KEY,", "").replace("_", "1").split("\\s*,\\s*"));
channelTemp.forEach(item -> metaObject.channel.add(Integer.parseInt(item)));
System.out.println("done");
}
Unfortunately, this throws a NullPointerException in the third line here and I don't have a clue why. I replaced _ with 1 for testing purposes to avoid a NumberFormatException. When I print out every object in the lambda function instead of adding them to my ArrayList<Integer>, I can see that all items have an Integer value. So why do I get an exception here?
Since you're almost there I'll give you a hand.
String line = "#KEY,_,0,1,2 , _,4,5,6,";
List<Integer> collect = Arrays.stream(line.replaceAll("#KEY|_", "").split(","))
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(Integer::valueOf).collect(Collectors.toList());
System.out.println(collect);
EDIT
To obtain the null you can alter the mapping process like:
List<Integer> collect = Arrays.stream(line.split(","))
.skip(line.startsWith("#KEY") ? 1 : 0)
.map(String::trim)
.filter(s -> !s.isEmpty())
.map(s -> "_".equals(s) ? null : Integer.valueOf(s)).collect(Collectors.toList());
You're trying to put in list of Integer a String:
metaObject.key1 = Arrays.asList(line.replace("#KEY,", "").replace("_", "").trim().split("\\s*,\\s*"));
Here line.replace(...) and trim() return a String, and split(...) returns a String[].
Therefore Arrays.asList(...) returns a List<String> here, that's not compatible with your definition of key1 (List<Integer>).
Yes, you can convert it to List<Integer> by call Integer.valueOf(...) or Integer.parseInt(...).
But I would recommend to
Use a new instance of List instead of Arrays.asList(...) because the latest one will produce an unmodifiable collection. Sometines it's not what you want :)
Use something less specific than your own text format. What about JSON? There are a lot of libraries to simplify parsing/storing of the data.
Firstly, you should split your string with ",", then you try if your each String is an integer or not with an isIntegerMethod. If it is an integer, you can add it into the list.
public static void main(String[] args) throws IOException {
String str = "#KEY,_,0,1,2,_,4,5,9";
String [] strArr = str.split(",");
List<Integer> intList = new ArrayList<Integer>();
for (String string : strArr) {
if (isInteger(string, 10)) {
intList.add(Integer.valueOf(string));
} else {
System.out.println(string + " is not an integer");
}
}
System.out.println(intList.toString());
}
public static boolean isInteger(String s, int radix) {
if(s.isEmpty()) return false;
for(int i = 0; i < s.length(); i++) {
if(i == 0 && s.charAt(i) == '-') {
if(s.length() == 1) return false;
else continue;
}
if(Character.digit(s.charAt(i),radix) < 0) return false;
}
return true;
}
If I have two class constants:
List<String> workingList= new ArrayList<String>();
StringBuilder holder = new StringBuilder(50);
both residing within, call it class StringParser and primary method readStuff()...
public class StringParser{
public void readStuff(){
//parsing logic and adding <String> elements to
//said workingList...
}//end of method readStuff
followed by a method where I inspect the contents of workingList...
public String someReaderMethod()
{
int ind = 0;
for(int i = 0; i < workingList.size();i++)
{
if(workingList.get(i).contains(someExp))
{
workingList.remove(ind);
holder.append(workingList.get(i).toString());
}
else
{
++ind;
}
}
return holder.toString();
}
...given that StringBuilder holder now contains what workingList has removed, is there a way I can 'pass' the contents of StringBuilder to a new ArrayList?
Is there a reason why you want to use a StringBuilder? You can directly insert the values into a new ArrayList. I think you could do it in a simpler way.
List<String> discardedList = new ArrayList<String>();
public void readStuff() {}
public static List<String> someReaderMethod()
{
for(int i = 0; i < workingList.size(); i++)
{
if(workingList.get(i).contains(someExp))
{
discardedList.add(workingList.get(i));
workingList.remove(i);
}
}
return discardedList;
}
You will need a deliminator to parse string and then you can use Split method and convert String[] to ArrayList.
holder.append(tempList.get(i));
holder.append(";");//Deliminator
Now when you have to use it you need to do
String[] strings =holderString.split(";");
List<String> list = Arrays.asList(strings);
While appending your List elements to your StringBuilder object, you need to append an extra delimiter after every append..
Later on, you can split the String in StringBuilder on that delimiter, and then convert your String array thus obtained to an ArrayList..
I have a series of String[] arrays which are list of words. Something like:
String[] ListOne = new String[100];
String[] ListTwo = new String[100];
/*And so on with other lists */
ListOne[0] = "word00";
ListOne[1] = "word01";
/*And so on till*/
ListLast[99] = "word 99 from last list";
Now I want a function for each list that, given a number returns the corresponding element (word):
public String GetFromListOne(int key) { return ListOne[key];}
Is there a way to avoid manually writing each of this getter functions?
In PHP, for example, I would just use the magic method __call,
or pass as an argument with the list name and reference it dynamically.
Is there a way to do something similar in Java?
Or an alternative strategy to achieve the same result?
You should look into inheritance.
What you basically must do is define an interface (or extend a List class)
public interface ListTest{
//**Gets keys from lists*//
GetFromListOne(int key);
}
then
public class Listone implements ListTest{
/** methods **//
GetFromListOne(int key);
/** methods **//
}
Have fun extending
http://docs.oracle.com/javase/tutorial/java/IandI/createinterface.html
You could use a 2 dimensional array, or a list of arrays and have your function take 2 parameters. One for the array that you want and the other for the element in the array.
2 dimensional array:
String[][] ListN = new String[100,100];
String getFromList(int n, int key) {
return ListN[n][key];
}
Or list of arrays:
List<String[]> listOfArrays = new ArrayList<String[]>();
listOfArrays.add(new String[100]);
listOfArrays.add(new String[100]);
String getFromList(int n, int key) {
return listOfArrays.get(n)[key];
}
Could you have a function that takes as input the key and the list number:
public String GetFromListOne(int list, int key) {
switch(list):
case 1:
return ListOne[key];
break;
case 2:
return ListTwo[key];
break;
...
}
or even better make an array of arrays:
String[][] ListOfLists = new String[10];
ListOfLists[0] = new String[100];
...
public String GetFromList(int list, int key) {
return ListOfLists[list][key];
}
Otherwise I don't know of a function to override like __call
String[] ListFour=new String[100];
String[] ListTwentyThree=new String[100];
String[] ListNine=new String[100];
String[] ListOne=new String[100];
Hashtable<Integer,String[]> yourlist=new Hashtable<Integer,String[]>();
yourlist.put(4, ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(9, ListNine);
yourlist.put(1, ListOne);
System.out.println(yourlist.get(4)[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(9)[1]);//first stringin ListNine
another version:
Hashtable<Object,String[]> yourlist=new Hashtable<Object,String[]>();
yourlist.put("two multiplied by two", ListFour);
yourlist.put(23, ListTwentyThree);
yourlist.put(0.03, ListNine);
yourlist.put(true, ListOne);
System.out.println(yourlist.get("two multiplied by two")[5]);//fifth string in ListFour
System.out.println(yourlist.get(23)[51]);//fifty first string in List23
System.out.println(yourlist.get(true)[1]);//first stringin ListNine
Based in the __call PHP method, you can achieve this implementing a method that receives the list and the index, and using generics you can get something like this.
public class Utility {
public <T> T getElementFromArray(T[] array, int index) {
if (index >= array.length || index < 0) return null;
return array[index];
}
}
The pitfall of this method is that can't be used for primitive array holders, like int[]. The solution for these cases would be using the wrapper classes for primitive types.
public static void main(String[] args) {
Utility u = new Utility();
String[] ss = new String[2];
ss[0] = "Hello";
ss[1] = "world!";
System.out.println(u.getElementFromArray(ss, 0));
System.out.println(u.getElementFromArray(ss, 1));
int[] ii = new int[2];
ii[0] = 5;
System.out.println(u.getElementFromArray(ii, 0)); //compile error
//Solution: use wrapper classes
Integer[] ii2 = new Integer[2];
ii2[0] = 5;
System.out.println(u.getElementFromArray(ii2, 0));
}
Try this code
List<String[]> lists = new ArrayList<String[]>();
public String getFromLists(int key) {
List<String> res = new ArrayList<String>();
for (String[] s: lists){
res.add(s[key]);
}
return res.get(key);
}
or better
public String getFromLists(int key) {
return lists.get(key)[key];
}