Добрый день мне необходимо подсчитать суммарную зарплату сотрудников по подразделениям. Данные я загружаю из csv файла. Для подсчёта суммарной з/п по подразделениям я использую Stream API. Версия java 8. Вот код моего метода:
public void oneMethod()
{
List<String> list1=new ArrayList<String>();
Map<String, Integer> nameSalary=new HashMap<String, Integer>();
// nameSalary=r.toList().stream().flatMap(x->Stream.of(x.getDivision().getName(),x.getSalary())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
///nameSalary=r.toList().stream().collect(Collectors.toMap(IPerson::getDivision,IPerson::getSalary));
///nameSalary=r.toList().stream().collect(Collectors.toMap(IPerson::getDivision,IPerson::getSalary));
list1=r.toList().stream().map(x->x.getDivision().getName()).collect(Collectors.toList());
Map<IDivision, Double> countDivisionSalary = r.toList().stream()
.collect(Collectors.toMap(IPerson::getDivision, Collectors.summarizingDouble(IPerson::getSalary)));
for (Map.Entry entry : countDivisionSalary.entrySet()) {
System.out.println("Podrazdelenie: " + entry.getKey()+"Sum Salary"+entry.getValue());
}
На этой строчке Map nameSalary=new HashMap(); Java выбивает следующее исключение:Exception in thread "main" java.lang.RuntimeException: Uncompilable source code - Erroneous tree type:
Код класса LoadRepository в котором происходит загрузка в csv файл (он также содержит метод oneMethod для подсчёта суммарной з/п по подразделениям):
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.laba1;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.function.Function;
import static java.util.function.Function.identity;
import java.util.stream.Collectors;
import static java.util.stream.Collectors.counting;
import static java.util.stream.Collectors.groupingBy;
import java.util.stream.Stream;
import javafx.util.Pair;
/**
*
* @author Data
*/
public class LoadRepository {
private Repository r;
private int size=2000;
public Repository getR() {
return r;
}
public void setR(Repository r) {
this.r = r;
}
public LoadRepository() {
r=new Repository(size);
}
public void readFromFileInRepository(String fileName) throws FileNotFoundException, IOException, Exception {
// Repository r = new Repository(2000);
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
File f = new File(fileName);
BufferedReader fin = new BufferedReader(new FileReader(f));
String line;
Scanner in = new Scanner(new File(fileName));
while (in.hasNextLine()) {
String buf = in.nextLine();
if (buf.startsWith("id")) {
;
} else {
String[] bufArray = buf.split(";");
int id = Integer.parseInt(bufArray[0]);
String firstName = bufArray[1];
String lastName = bufArray[2];
Gender gender = Gender.valueOf(bufArray[3].toUpperCase());
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd.MM.yyyy");
LocalDate date = LocalDate.parse(bufArray[4], formatter);
String Name = bufArray[5];
IDivision div = new Division(Name);
BigDecimal money = new BigDecimal(bufArray[6]);
IPerson bufObject = new Person(id, firstName, lastName, gender, date, div, money);
if (bufObject != null) {
r.add(bufObject);
}
}
}
}
public Stream<IPerson> threeMethod()
{
return r.toList().stream().filter(s -> s.getFirstName().contains("aa"));
//stream.filter(s -> s.getFirstName().contains("AA"));
//return stream;
}
public Stream<IPerson> twoMethod()
{
BigDecimal valDouble = new BigDecimal(5000);
return r.toList().stream().filter(s -> s.getFirstName().contains("a")).filter(s->s.getAge()>30).filter(s->s.getSalary().compareTo(valDouble)<0);
//stream.filter(s -> s.getFirstName().contains("AA"));
//return stream;
}
public Map<Integer, Long> fourMethod()
{
// BigDecimal valDouble = new BigDecimal(5000);
// return r.toList().stream().filter(s -> s.getFirstName().contains("a")).filter(s->s.getAge()>30).filter(s->s.getSalary().compareTo(valDouble)<0);
//stream.filter(s -> s.getFirstName().contains("AA"));
//return stream;
// Map<Integer,Integer> hm= new HashMap<>();
// HashMap<int,int>= r.toList().stream().collect(Collectors.toMap(IPerson,0));
// hm.put(r.toList().stream().filter(s->s.getBirthdate().getYear()>0), size);
Set<Integer> set1=new HashSet<Integer>();
Set<Integer> set2=new HashSet<Integer>();
List<Integer> list1=new ArrayList<Integer>();
set1=r.toList().stream().map(x->x.getBirthdate().getYear()).collect(Collectors.toSet());
list1=r.toList().stream().map(x->x.getBirthdate().getYear()).collect(Collectors.toList());
r.toList().stream().filter(s->s.getBirthdate().getYear()==s.getBirthdate().getYear()).count();
// r.toList().stream().map(x->x.getBirthdate().getYear()).map(x->x.getBirthdate().getYear());
// Set<Integer> duplicated = r.toList().stream().map(x->x.getBirthdate().getYear()).filter(i -> Collections.frequency(r.toList().stream().map(x->x.getBirthdate().getYear()), i) >1)
// .collect(Collectors.toSet());
/* System.out.println("Years:");
for(int i:set1) System.out.println(i);
System.out.println("Count of years:");
for(int i:duplicated) System.out.println(i);*/
/*Map<Integer, Integer> yearDuplicates = new HashMap<Integer, Integer>();
yearDuplicates.put(r.toList().stream().map(x->x.getBirthdate().getYear()), r.toList().stream().map(x->x.getBirthdate().getYear()).count());
System.out.println("Years duplicates:");
for (Map.Entry entry : yearDuplicates.entrySet()) {
System.out.println("Year: " + entry.getKey() + " Count: "
+ entry.getValue());
}*/
// Map<Integer, Integer> letterToCount =
// list1.stream().collect(groupingBy(identity(), counting()));
// return r.toList().stream().collect(Collectors.toMap(Function.identity(), v -> 1L, Long::sum));
/* Set<Integer> set3= set2.stream()
.filter(t -> Collections.frequency(r.toList().stream().map(x->x.getBirthdate().getYear()), t) > 1).collect(Collectors.toSet());*/
/* System.out.println("Count years");
for(int i:set3) System.out.println(i);*/
Map<Integer, Long> countForYear = list1.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
/*for (Map.Entry entry : countForYear.entrySet()) {
System.out.println("Year: " + entry.getKey() + " Count: "
+ entry.getValue());
}*/
return countForYear;
}
public void oneMethod()
{
List<String> list1=new ArrayList<String>();
Map<String, Integer> nameSalary=new HashMap<String, Integer>();
// nameSalary=r.toList().stream().flatMap(x->Stream.of(x.getDivision().getName(),x.getSalary())).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));
///nameSalary=r.toList().stream().collect(Collectors.toMap(IPerson::getDivision,IPerson::getSalary));
///nameSalary=r.toList().stream().collect(Collectors.toMap(IPerson::getDivision,IPerson::getSalary));
list1=r.toList().stream().map(x->x.getDivision().getName()).collect(Collectors.toList());
Map<IDivision, Double> countDivisionSalary = r.toList().stream()
.collect(Collectors.toMap(IPerson::getDivision, Collectors.summarizingDouble(IPerson::getSalary)));
for (Map.Entry entry : countDivisionSalary.entrySet()) {
System.out.println("Podrazdelenie: " + entry.getKey()+"Sum Salary"+entry.getValue());
}
}
}
Код класса Person - в нём фигурируют поля IDivision(ссылка на интерфейс IDivision который реализует класс Division):
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.laba1;
import java.math.BigDecimal;
import org.joda.time.DateTime;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import org.joda.time.Period;
/**
* Class Person contains four field: 1) id as identifikator; 2) Name-Name Father
* Surname; 3) date - date birthday 4) sex - sex Person
*
* Methods getDate(),getSex(),getId(), getName() -returns values fields class
* Methods setDate(),setSex(),setId(), setName() -set values fields class
*
* Method difference_date() -calcute age Person
*
* @author Data
*/
public class Person implements IPerson {
/**
* Filed "id" as identifikator.
*
*/
private int id;
/**
* Filed "Name"-Name Father Surname.
*
*/
private String FirstName;
private String LastName;
private LocalDate Birthdate;
/**
* Filed date - date birthday.
*
*/
/**
* Filed Gender - sex Person.
*
*/
private Gender Gender;
/**
* Filed Salary - Salary for Person.
*
*/
private BigDecimal Salary;
public IDivision IDivision;
/**
* Method getId() return Id.
*
* @return
*/
public Integer getId() {
return id;
}
/**
* Method setId set field Id.
*
* @param id
*/
public final void setId(Integer id) {
this.id = id;
}
/**
* Method getFirstName return filedt FirstName.
*
*/
public String getFirstName() {
return FirstName;
}
/**
* Method getFirstName set filed FirstName.
*
* @param FirstName
*/
public String setFirstName(String FirstName) {
this.FirstName = FirstName;
return this.FirstName;
}
/**
* Method getlastName return filed LastName.
*
*/
public String getLastName() {
return LastName;
}
/**
* Method setLastName set filed LastName.
*
* @param FirstName
*/
public String setLastName(String LastName) {
this.LastName = LastName;
return this.LastName;
}
/**
* Method getBirthdate return filed Birthdate.
*
*/
public LocalDate getBirthdate() {
return Birthdate;
}
/**
* Method setBirthdate set filed Birthdate.
*
* @param Birthdate
*/
public LocalDate setBirthdate(LocalDate Birthdate) {
this.Birthdate = Birthdate;
return this.Birthdate;
}
/**
* Method getSalary return filed Salary.
*
*/
public BigDecimal getSalary() {
return Salary;
}
/**
* Method setSalary set filed Salary.
*
* @param Salary
*/
public void setSalary(BigDecimal Salary) {
this.Salary = Salary;
}
/**
* Method getGender return gender Person.
*
*/
public Gender getGender() {
return Gender;
}
/**
* Method setGender set gender Person.
*
* @param Gender
*/
public void setGender(Gender Gender) {
this.Gender = Gender;
}
/**
* Method getDivision return gender Person.
*
*/
public IDivision getDivision() {
return IDivision;
}
/**
* Method getDivision return field setDivision.
*
* @param division
*/
public void setDivision(IDivision division) {
this.IDivision = IDivision;
}
/**
* This is constructor.
*
* @param id
* @param FirstName
* @param Name
* @param Birthdate
* @param Gender
* @param Salary
*
*/
public Person(int id, String FirstName, String LastName, Gender Gender,LocalDate Birthdate, String Name, BigDecimal Salary) {
this.id = id;
this.FirstName = FirstName;
this.LastName = LastName;
this.Gender = Gender;
this.Birthdate = Birthdate;
this.IDivision.setName(Name);
this.Salary = Salary;
}
public Person(int id, String FirstName, String LastName,Gender Gender, LocalDate Birthdate, IDivision IDivision, BigDecimal Salary ) {
this.id = id;
this.FirstName = FirstName;
this.LastName = LastName;
this.Gender = Gender;
this.Birthdate = Birthdate;
this.IDivision = IDivision;
this.Salary = Salary;
}
/**
* Method getAge calculate and print age Person.
*/
public Integer getAge() {
LocalDate now = LocalDate.now();
//Period p = new Period(date, now);
int years = (int) ChronoUnit.YEARS.between(Birthdate, now);
return years;
}
}
Код класса Division:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mycompany.laba1;
/**
*
* @author Data
*/
public class Division implements IDivision {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public Division( String name) {
this.name = name;
}
}
Код класса Repository(в нём используется метод toList(), который преобразует массив объектов класса Person в коллекцию):
package com.mycompany.laba1;
import java.time.format.DateTimeFormatter;
import java.util.Locale;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.*;
import java.io.*;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.Month;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Scanner;
import java.util.function.Predicate;
import java.util.Optional;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Class Repository is intended for store objects class IPerson.
*
*
* @author Data
*/
public class Repository implements IRepository {
/**
* Field size store size massiv.
*/
private int size;
private IPerson[] mass;
private int count = 0;
/**
* This is constructor. In constructor we initialize property size and array
* mass of type IPerson
*
*
* @author Data
* @param size
*/
public Repository(int size) {
this.size = size;
mass = new IPerson[size];
}
/**
* Method setSize set size.
*
* @param size
*/
public final void setSize(int size) {
this.size = size;
}
/**
* Method getSize return size.
*
* @return
*/
public final int getSize() {
return size;
}
/**
* Method add -add Object into array mass.
*
*/
public void add(IPerson person) {
/* if (count == size)
{
int currentCapacity = mass.length;
IPerson[] tempArr = new IPerson[currentCapacity + currentCapacity];
for(int i = 0; i < mass.length; i++) {
tempArr[i] = mass[i];
}
mass = tempArr;
}*/
int firstLength = mass.length;
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null && i == mass.length - 1) {
int currentCapacity = mass.length;
IPerson[] tempArr = new IPerson[currentCapacity * 2];
for (int j = 0; j < currentCapacity; j++) {
tempArr[j] = mass[j];
}
// mass = new IPerson[tempArr.length];
mass = tempArr;
// mass[currentCapacity]=obj;
// break;
}
if (mass[i] == null) {
mass[i] = person;
break;
}
}
//else
}
/**
* Method add -add Object into array mass, if element mass[index] is null.
*
*/
public void add(int index, IPerson person) {
if (mass[index] == null) {
mass[index] = person;
} else //throw new Exception("This index contains element");
{
Optional.of("This index contains element");
}
}
/**
* Method set -replace element array "mas" with "index" for object "person".
*
* @param index
* @param person
*/
public IPerson set(int index, IPerson person) {
mass[index] = person;
return person;
}
/**
* Method get -return element array "mass" for given "index".
*
*/
public IPerson get(int index) {
return mass[index];
}
/**
* Method toList -convert array "mass" to Collection "List".
*
*/
public List<IPerson> toList() {
ArrayList<IPerson> arr = new ArrayList<>();
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null) {
arr.add(mass[i]);
}
}
return arr;
}
/**
* Method delete(int index) receive index element massiv and delete this
* element.
*
* @param index
*/
public IPerson delete(int index) {
/* int size2 = mass.length - 1;
IPerson[] mass2 = new IPerson[size2];
System.arraycopy(mass, 0, mass2, 0, index);
System.arraycopy(mass, index + 1, mass2, index,
mass.length - index - 1);
// count--;
mass = new IPerson[size2];
System.arraycopy(mass2, 0, mass, 0, size2);
mass[index+1]=null;*/
/* for (int i = index; i < mass.length-1; i++)
{
mass[i] = mass[i + 1];
}
int[] newArr = new int[mass.length - 1];
System.arraycopy(mass, 0, newArr, 0, mass.length - 1);*/
// return mass[index];
IPerson oldValue = mass[index];
int numMoved = count - index - 1;
if (numMoved > 0) {
System.arraycopy(mass, index+1, mass, index, numMoved);
}
mass[--count] = null;
return oldValue;
}
/**
* Method getMass - return array "mass"
*
*/
public IPerson[] getMass() {
int countNotNullElement = 0;
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null) {
countNotNullElement++;
}
}
int currentIndex = 0;
IPerson[] mass2 = new IPerson[countNotNullElement];
for (int i = 0; i < mass.length; i++) {
if (mass[i] != null) {
mass2[currentIndex++] = mass[i];
}
}
// mass=mass2;
return mass2;
}
/**
* Method readFromFileInRepository - read file and add to array "mass" with
* method add(IPerson obj)
*
* @param fileName
*/
/**
* Method SortBy-sort array "mass" with given comparator
*
* @param comparator
*/
public void sortBy(Comparator<IPerson> comparator) {
/* BubbleSorter bs=new BubbleSorter();
try {
bs.bubbleSort(comparator);
} catch (InstantiationException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
}*/
InsertionSorter is=new InsertionSorter();
try {
is.insertionSort(Comparators.salary);
} catch (InstantiationException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalArgumentException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchFieldException ex) {
Logger.getLogger(Repository.class.getName()).log(Level.SEVERE, null, ex);
}
}
public void bubbleSort(Comparator<IPerson> comparator) {
for (int i = 0; i < mass.length; i++) {
for (int j = mass.length-1 ; j > i; j--) {
if (comparator.compare(mass[j-1], mass[j])>0) {
IPerson buf = mass[j - 1];
mass[j - 1] = mass[j];
mass[j] = buf;
}
}
}
}
public void insertionSort(Comparator<IPerson> comparator) {
IPerson temp;
int item;
for (int counter = 1; counter < mass.length; counter++) {
temp = mass[counter];
item = counter - 1;
while (item >= 0 && comparator.compare(mass[item], temp)>0) {
mass[item + 1] = mass[item];
mass[item] = temp;
item--;
}
}
}
public IRepository searchBy(Predicate<IPerson> condition) {
IRepository buf = new Repository(size);
IDivision div = new Division("A");
IDivision div2 = new Division("B");
IDivision div3 = new Division("C");
// System.out.println("Hello World");
LocalDate localDate1 = LocalDate.of(1960, Month.MAY, 14);
LocalDate localDate2 = LocalDate.of(1965, Month.MAY, 14);
LocalDate localDate3 = LocalDate.of(1970, Month.MAY, 14);
BigDecimal bd = new BigDecimal(20000);
BigDecimal bd2 = new BigDecimal(25000);
BigDecimal bd3 = new BigDecimal(35000);
IPerson p1 = new Person(1, "Valeriy", "Petrov",Gender.MALE, localDate1, div, bd);
IPerson p2 = new Person(5, "Valeriy", "Petrov",Gender.MALE, localDate1, div, bd);
IPerson p3 = new Person(6, "Valeriy", "Petrov",Gender.MALE, localDate1, div2, bd);
IPerson p4 = new Person(7, "Valeriy", "Petrov", Gender.MALE,localDate2, div, bd);
IPerson p5 = new Person(8, "Valeriy", "Petrov", Gender.MALE,localDate1, div, bd);
IPerson p6 = new Person(9, "Vera", "Petrova",Gender.FEMALE, localDate1, div3, bd2);
IPerson p7 = new Person(10, "Ivan", "Ivanov", Gender.MALE,localDate3, div, bd);
IPerson p8 = new Person(0, "Vladimir", "Smirnov",Gender.MALE, localDate1, div, bd3);
buf.add(p1);
buf.add(p2);
buf.add(p3);
buf.add(p4);
for (int i = 0; i < buf.toList().size(); i++) {
if (condition.test(mass[i])) {
return buf;
}
}
return buf;
}
}
Вот как выглядит загружаемый csv файл:
Подскажите пожалуйста как разобраться с этой проблемой.
Netbeans позволяет запускать код, даже если некоторые классы не компилируются. Это, правда, приводит к неприятным эффектам, когда пытаемся обратиться к не скомпилированному классу, конкретно, к Uncompilable source code - Erroneous tree type
.
Попробуй отключить настройку "Compile on save" в свойствах проекта (Build -> Compiling).
Так же ошибка могла быть вызвана кешированием. Ниже ссылка на англоязычное обсуждение этой ошибки - много дельных советов:
https://stackoverflow.com/questions/2333285/java-lang-runtimeexception-uncompilable-source-code-what-can-cause-this
И да, код вообще компилируется?
Айфон мало держит заряд, разбираемся с проблемой вместе с AppLab
Проблема такая: На главном активити у меня есть кнопкаПо нажатмю на неё я запускаю сканнер QR от ZXING, считываю сам код и сохраняю его
Вопрос инициирован топиком: Плавный морфинг одного path в другой path
решил читься верстать на bootstrap, но сразу возникло пару проблем