Java: Arraylist of Array - java

I want to make an arraylist of an array of 2 elements. So, I have unknown rows and known columns (i.e. 2).
E.g. [{name1, ID1}, {name2, ID2}, ...]
I also have to return this arraylist.
I tried using
ArrayList<arr> alist = new ArrayList<arr>();
but don't know how to proceed.
Please advise.

When you define a ArrayList must use a class. In this case, you can use a class Person:
class Person {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Then, we can define a ArrayList of Persons:
ArrayList<Person> array = new ArrayList<Person>();
array.get(0).getId();
array.get(0).getName();

I have put here two simple ways to do it. However, you can think of many more such ways.
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class Main {
public static void main(String[] a) {
List<String[]> list = new ArrayList<>();
String[] arr;
arr = new String[2];
arr[0] = "name1";
arr[1] = "ID1";
list.add(arr);
arr = new String[2];
arr[0] = "name2";
arr[1] = "ID2";
list.add(arr);
// Test
for (String[] arrElem : list) {
System.out.println(arrElem[0] + "\t" + arrElem[1]);
}
// Another option is to create a list of maps
List<Map<String, String>> list2 = new ArrayList<>();
Map<String, String> map = null;
map = new HashMap<>();
map.put("name1", "ID1");
list2.add(map);
map = new HashMap<>();
map.put("name2", "ID2");
list2.add(map);
// Test
for (Map<String, String> mapElem : list2) {
System.out.println(mapElem);
}
}
}
Output:
name1 ID1
name2 ID2
{name1=ID1}
{name2=ID2}

Related

Is it possible to clone names from the list to the specific array without creating a loop?

I have 35 categories inside this list List<CategoriesModel> categoriesModelList;, and I want to clone all names and put them inside this array String[] namesList, I'm currently cloning names using this code but I want to ask is there any method can clone names from list to the specific array without creating a loop?
String[] namesList = new String[categoriesModelList.size()];
for (int i = 0; i < categoriesModelList.size(); i++)
namesList[i] = categoriesModelList.get(i).getName();
CategoriesModel.java
public class CategoriesModel {
private int id;
private String name;
private boolean supportSubcategories;
public CategoriesModel(int id, String name, boolean supportSubcategories) {
this.id = id;
this.name = name;
this.supportSubcategories = supportSubcategories;
}
public int getId() {
return id;
}
public String getName() {
return name;
}
public boolean isSupportSubcategories() {
return supportSubcategories;
}
}
You could use a stream:
String[] namesList = categoriesModelList.stream()
.map(CategoriesModel::getName)
.toArray(String[]::new);
anyway you have to use loop operation.
but stream is more elegant.
String[] namesList = categoriesModelList.stream()
.map(CategoriesModel::getName)
.toArray(String[]::new);
Use java.util.stream for it:
String[] names = categoriesModelList.stream()
.map(category -> category.getName())
.collect(Collectors.toList())
.toArray(new String[]{});
Another variant avoid stream():
List<String> namesList = new LinkedList<>();
categoriesModelList.forEach(category -> namesList.add(category.getName()));
String[] names = namesList.toArray(new String[]{});
But this is just a workaround

Add 2 arraylists into 1 with same index value

I know this question is kind of repetitive But still I can't get an answer.
I have 2 arraylists containing name and description respectively as
final ArrayList<String> arrayOne = new ArrayList<String>(); // containing names
final ArrayList<String> arraytwo = new ArrayList<String>(); // containing description
I need a view like
I have tried
arraytwo.add(arrayOne);
&
arrayThree.addAll(arrayOne);
arrayThree.addAll(arrayTwo);
But can't a desired arraylist.
Regards
POJO class
public class Model
{
String name;
String desc;
public String getName() {
return name;
}
public void setName(String name) {
this.name= name;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
desc = desc;
}
}
For Storing to arraylist
ArrayList<Model> arrayModel = new ArrayList<Model>();
for(int i=0;i<arrayOne.size();i++)
{
Model model=new Model();
model.setName(arrayOne.get(i));
model.setDesc(arrayTwo.get(i));
arrayModel.add(model);
}
If you don't want to create POJO, try this:
List<String> nameList;
List<String> desList;
//for storing
Map<String, String> map = new HashMap<>();
for(int i=0;i<nameList.size();i++) {
map.put(nameList.get(i), desList.get(i));
}
//for retrieving
for(Map.Entry<String, String> m : map.entrySet())
String nameListItem = m.getKey();
String desListItem = m.getValue();
}

Java 8 groupingby with custom key

I have a series of input Strings in the following format:
typeA:code1,
typeA:code2,
typeA:code3,
typeB:code4,
typeB:code5,
typeB:code6,
typeC:code7,
...
and I need to get a Map<String, List<String>> with the following structure:
typeA, [code1, code2, code3]
typeB, [code4, code5, code6]
typeC, [code7, code8, ...]
The catch is that to generate each type I need to call a function like this one on each input String:
public static String getType(String code)
{
return code.split(":")[0]; // yes this is horrible code, it's just for the example, honestly
}
I'm pretty confident that Streams and Collectors can do this, but I'm struggling to get the right incantation of spells to make it happen.
The code becomes simple if you consider what you have omitted, that you need the second part of the split string as well:
Map<String, List<String>> result = Stream.of(input).map(s->s.split(":", 2))
.collect(groupingBy(a->a[0], mapping(a->a[1], toList())));
(assuming you have a import static java.util.stream.Collectors.*;)
There is nothing wrong with splitting a String into an array, the implementation has even a “fast-path” for the common case you are splitting using a single simple character instead of a complicate regular expression.
Here is one way to do it (assuming the class is named A):
Map<String, List<String>> result = Stream.of(input)
.collect(groupingBy(A::getType, mapping(A::getValue, toList())));
If you want the output sorted you can use a TreeMap instead of the default HashMap:
.collect(groupingBy(A::getType, TreeMap::new, mapping(A::getValue, toList())));
Full example:
public static void main(String[] args) {
String input[] = ("typeA:code1," +
"typeA:code2," +
"typeA:code3," +
"typeB:code4," +
"typeB:code5," +
"typeB:code6," +
"typeC:code7").split(",");
Map<String, List<String>> result = Stream.of(input)
.collect(groupingBy(A::getType, mapping(A::getValue, toList())));
System.out.println(result);
}
public static String getType(String code) {
return code.split(":")[0];
}
public static String getValue(String code) {
return code.split(":")[1];
}
Although I was too slow, here is an MCVE showing how this can be solved with Collectors#groupingBy.
There are obviously different options for defining the "classifier" and "mapper". Here I'm simply using String#substring to find the part before and after the ":".
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.mapping;
import static java.util.stream.Collectors.toList;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
public class GroupingBySubstringsTest
{
public static void main(String[] args)
{
List<String> strings = new ArrayList<String>();
strings.add("typeA:code1");
strings.add("typeA:code2");
strings.add("typeA:code3");
strings.add("typeB:code4");
strings.add("typeB:code5");
strings.add("typeB:code6");
strings.add("typeC:code7");
Map<String, List<String>> result = strings.stream().collect(
groupingBy(s -> s.substring(0, s.indexOf(":")),
mapping(s -> s.substring(s.indexOf(":")+1), toList())));
for (Entry<String, List<String>> entry : result.entrySet())
{
System.out.println(entry);
}
}
}
Consider Student Class:
public Student(String name, Address add) {
super();
this.name = name;
this.add = add;
}
private String name;
private Address add;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Address getAdd() {
return add;
}
public void setAdd(Address add) {
this.add = add;
}
}
And Address class:
class Address{
public Address(String city, String state) {
super();
this.city = city;
State = state;
}
private String city;
private String State;
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return State;
}
public void setState(String state) {
State = state;
}
}
Now, if I want to group Student based on City & State which is part of Address class:
Student s1 = new Student("Rohit", new Address("Mumbai", "MH"));
Student s2 = new Student("Sudeep", new Address("Mumbai", "MH"));
Student s3 = new Student("Amit", new Address("Pune", "MH"));
Student s4 = new Student("Rahul", new Address("Blore", "KR"));
Student s5 = new Student("Vishal", new Address("Blore", "KR"));
List<Student> st = Arrays.asList(s1,s2,s3,s4,s5);
Function<Student, String> compositeKey = studRecord -> studRecord.getAdd().getCity()+":"+ studRecord.getAdd().getState();
Map<String, List<Student>> groupedStudent = st.stream()
.collect(Collectors.groupingBy(compositeKey));

Java: Storing an Array into an Array?

Is it possible to store three string values added into an array (studentName), and store that into a different array so it can be found later?
Basically my main goal is to store a name, user id, and a balance (fullName, idName, 300).
And add that into a "super(?)" array so when people type down, it finds the fullName and pulls the information from there.
You can create a class
public class Student {
private String name;
private String id;
private int balance;
}
and then you can create a list of these objects:
List<Student> list = new ArrayList<Student>();
Map<String, String> map = new HashMap<String, String>();
then:
List<Map<String, String>> listOfMaps = new ArrayList<Map<String, String>>();
and then:
map.put("name", "Thomas");
map.put("id", "Thomas id");
map.put("balance", ""300);
listOfMaps.add(map);
Anyhow, be careful. You will have to keep numbers (f.e. balance) as a String and after you will need to map it.
Well, I believe you are talking about something like Jagged Array which is available in C# but for java, we can do it in some other ways... like creating a class and manipulating it as Generic List implementation...
public class Student {
private String name;
private int id;
private int balanace;
public Student(){}
public Student(String name, int id, int balance){
this.name = name;
this.id = id;
this.balanace = balance;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getBalanace() {
return balanace;
}
public void setBalanace(int balanace) {
this.balanace = balanace;
}
}
In some other class where you would want to manipulate
public class ManipulateData {
public static void main(String[] args){
Student student1 = new Student("James", 1, 500);
List<Student> list = new ArrayList<Student>();
list.add(student1);
for(Student s: list){
System.out.println("Name : " + s.getName());
System.out.println("ID : " + s.getId());
System.out.println("Balance : " + s.getBalanace());
}
}
}

Sort JList by name

What I am doing is getting elements from a map and adding them onto a JList to display on a GUI. I want to know how to sort the names alphabetically.
private void refreshShopsList() {
gameShopsJList.setModel(new javax.swing.AbstractListModel<String>() {
public int getSize() {
return ShopsLoader.getShops().size();
}
public String getElementAt(int i) {
return getShopByIndex(i).getName();
}
});
}
private Shop getShopByIndex(int index) {
Iterator<Entry<String, Shop>> it = ShopsLoader.getShops().entrySet().iterator();
int count = -1;
while(it.hasNext()) {
Entry<String, Shop> entry = it.next();
count++;
if (count == index)
return entry.getValue();
}
return null;
}
/**
* The map of the shops
*/
private static final Map<String, Shop> shops = new HashMap<String, Shop>();
public static Map<String, Shop> getShops() {
return shops;
}
Here is a little example, which sorts your shop names.
The ShopComparator class does the sorting task:
package model;
import java.util.Comparator;
public class ShopComparator implements Comparator<Shop> {
#Override
public int compare(Shop o1, Shop o2) {
return o1.getName().compareTo(o2.getName());
}
}
The Shop class, as simple as possible:
package model;
public class Shop {
private int id;
private String name;
public Shop(int id, String name) {
super();
this.id = id;
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
And the main app:
package model;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.TreeSet;
public class App {
public static void main(String[] args) {
Map<String, Shop> shops = new HashMap<String, Shop>();
Shop s1 = new Shop(1, "Apus Drugstore");
Shop s2 = new Shop(2, "DM");
Shop s3 = new Shop(3, "Kaufhof");
Shop s4 = new Shop(4, "Moes Traverne");
shops.put("one", s3);
shops.put("two", s4);
shops.put("three", s1);
shops.put("four", s2);
for(Shop s : shops.values()) {
System.out.println(s.getName());
}
ShopComparator sc = new ShopComparator();
TreeSet<Shop> sortedShops = new TreeSet<>(sc);
sortedShops.addAll(shops.values());
for(Shop s : sortedShops) {
System.out.println(s.getName());
}
}
}
First output, unsorted:
Moes Traverne
Kaufhof
Apus Drugstore
DM
and the sorted output.
Apus Drugstore
DM
Kaufhof
Moes Traverne
Algorithm:
get all values from JList, convert them to strings, store in array
sort the array
set new values to JList.
code:
JList jl = new JList(new Object[]{4.5,1,"Hi!"});
ListModel model = jl.getModel();
String[] strings = new String[model.getSize()];
for(int i=0;i<strings.length;i++){
strings[i]=model.getElementAt(i).toString();
}
Arrays.sort(strings);
jl.setListData(strings);
see about Comparator if you need to sort array in any other order.

Categories

Resources